user3282963
user3282963

Reputation: 13

how to write nested json using jsoncpp in c++

{
    "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++

Upvotes: 1

Views: 3704

Answers (2)

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;
}

Upvotes: 0

mpromonet
mpromonet

Reputation: 11942

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);  
}

Upvotes: 1

Related Questions