1)数据内嵌json
{
"code" : "SheBeiLiXianGaoJingShangChuan",
"params" :
{
"alarm_source" : "192.68.1.0",
"id" : "234",
"remark" : "fire alarm",
"time_alarm" : "2017-2-1 21:34:21"
}
}
Json::Value jsonCode;
jsonCode["code"] ="SheBeiLiXianGaoJingShangChuan";
Json::Value jsonParams;
jsonParams["id"] ="234";
jsonParams["remark"] = "firealarm";
jsonParams["time_alarm"] ="2017-2-1 21:34:21";
jsonParams["alarm_source"] ="192.68.1.0";
jsonCode["params"] = jsonParams;
2)数据内嵌字符串数组
{
"extra_fields":[
"custom_field_1",
"custom_field_2"
],
"surveillance_ids":[
"0"
],
"order":{
"timestamp":-1
},
"hit_condition":{
"hit_similarity":80
},
"start":0,
"limit":100
}
代码
Json::Value root;
Json::Value jsonExtraFields;
jsonExtraFields.append("custom_field_1");
jsonExtraFields.append("custom_field_2");
root["extra_fileds"] = jsonExtraFields;
Json::Value jsonSurveillanceIds;
jsonSurveillanceIds.append("0");
root["surveillance_ids"] = jsonSurveillanceIds;
Json::Value jsonTimestamp;
jsonTimestamp["timestamp"] = -1;
root["order"] = jsonTimestamp;
Json::Value jsonHitSimilarity;
jsonHitSimilarity["hit_similarity"] = 80;
root["hit_condition"] = jsonHitSimilarity;
root["start"] = 0;
root["limit"] = 100;
std::string strResult = root.toStyledString();
3)创建一个标准带有缩进格式的json文件
void WriteContentToJsonFile()
{
Json::Value root;
for (int i = 0; i < 10; i++)
{
Json::Value node;
node["zoom"] = 1;
root["data"].append(node);
}
cout << "直接输出:" << endl;
Json::FastWriter fw;
cout << fw.write(root) << endl ;
//直接输出的没有进行换行,查看困难
cout << "缩进输出:" << endl;
Json::StyledWriter sw;
cout << sw.write(root) << endl ;
ofstream ofstreamHandle;
ofstreamHandle.open("fengyuzaitu51cto.json");
ofstreamHandle << sw.write(root);
ofstreamHandle.close();
}
注意事项
Json::Value valueNodeList;
for(int i=0; i <3; i++)
{
Json::Value nodeChannel;
nodeChannel["id"] = i;
valueNodeList.append(nodeChannel);
}
Json::Value valueRoot;
std::cout<<valueNodeList.size()<<std::endl;\\输出3
valueRoot["channel"] = valueNodeList;
std::cout<<valueNodeList.size()<<std::endl;\\输出0
进行如上的赋值操作之后,不能再调用valueNodeList访问数组,例如调用valueNodeList.size访问到的数据始终返回0,因为数据已经迁移到valueRoot对象中。
转载于:https://blog.51cto.com/fengyuzaitu/2347657