JsonCpp第三课 生成json格式

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


上一篇:JsonCpp第一课 数据读取


下一篇:C++ 解析Json——jsoncpp