{
"id": "1234567890",
"seatbid":
[
{
"bid" :
[
{
"id": "1",
"crid" : "creative112",
}
],
"seat" : "512"
}
]
}
我是c ++和Jsoncpp的新手。我可以使用jsoncpp编写普通的json但是我不能像上面那样编写嵌套的jason。你可以教我如何在c ++中使用jsoncpp编写嵌套的json
答案 0 :(得分:1)
这是一个直截了当的解决方案:
#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);
}
答案 1 :(得分:0)
如果您打算像这样嵌套一个:
{
"id" : "1234567890",
"seatbid" : {
"bid" : {
"crid" : "creative112",
"id" : "1"
},
"seat" : "512"
}
}
以下代码可能是您想要的:
#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;
}