1
{
    "id": "1234567890",
    "seatbid": 
    [
        {
            "bid" : 
            [
                {
                    "id": "1",
                    "crid" : "creative112",
                }
            ],
            "seat" : "512"
        }
    ]
}

I am new to c++ and Jsoncpp .I can write normal json using jsoncpp but i can not write nested jason like above .Can you teach me how to write nested json using jsoncpp in c++

2

2 Answers 2

1

Here is a streightforward solution :

#include <json/json.h>
int main()
{   
    Json::Value bid0;
    bid0["id"] = "1";
    bid0["crid"] = "creative112";

    Json::Value bid;
    bid.append(bid0);

    Json::Value seatbid0;
    seatbid0["bid"] = bid;
    seatbid0["seat"] = "512";

    Json::Value seatbid;
    seatbid.append(seatbid0);

    Json::Value root;
    root["id"] = "1234567890";  
    root["seatbid"]=seatbid;

    Json::StyledWriter styledWriter;
    std::cout << styledWriter.write(root);  
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you intend to nest one inside another like:

{
   "id" : "1234567890",
   "seatbid" : {
      "bid" : {
         "crid" : "creative112",
         "id" : "1"
      },
      "seat" : "512"
   }
}

The following code might be what you are looking for:

#include <iostream>
#include "JsonCpp/jsoncpp.h"
using namespace std;

class IdCrid : public IJsonSerializable {

public:
    IdCrid() :id(""), crid("") {}

    virtual void Serialize(Json::Value& root) {
        root["id"] = id;
        root["crid"] = crid;
    }

    virtual void Deserialize(Json::Value& root) {
    }
    string id;
    string crid;
};

class SeatBid : public IJsonSerializable {

public:
    SeatBid() :seat("") {}

    virtual void Serialize(Json::Value& root) {
        bid.Serialize(root["bid"]);
        root["seat"] = seat;
    }

    virtual void Deserialize(Json::Value& root) {
    }
    string  seat;
    IdCrid bid;
};


class IdSeatbid : public IJsonSerializable {
public:
    IdSeatbid() :id(""){}

    virtual void Serialize(Json::Value& root) {
        root["id"] = id;
        seatbid.Serialize(root["seatbid"]);
    }

    virtual void Deserialize(Json::Value& root) {
    }
    string id;
    SeatBid seatbid;
};


void printJSON() {
    IdCrid ic;
    ic.id = "1";
    ic.crid = "creative112";

    SeatBid sb;
    sb.bid = ic;
    sb.seat = "512";

    IdSeatbid jp;
    jp.id = "1234567890";
    jp.seatbid = sb;

    string outString = "";
    CJsonSerializer::Serialize(&jp, outString);
    fprintf(stdout, "%s", outString.c_str());
}

int main()
{
    printJSON();
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.