jsoncpp 嵌入式linux,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();

}

4)构建一个空数组元素

Json::Value root;

Json::Value nodeRoot;

nodeRoot.resize(0);

root["sessionid"] = "123456";

root["node"] = nodeRoot;

std::string strMsg = root.toStyledString();

内存报文:

{

"node" : [],

"sessionid" : "123456"

}

提醒

Json::Value root;

Json::Value nodeRoot;

Json::Value node;

nodeRoot.append(node);

root["node"] = nodeRoot;

std::string strMsg = root.toStyledString();

生成的报文

{

"node" : [ null ]

}

里面是带有null字段的数组

注意事项

Json::Value valueNodeList;

for(int i=0; i <3; i++)

{

Json::Value nodeChannel;

nodeChannel["id"] = i;

valueNodeList.append(nodeChannel);

}

Json::Value valueRoot;

std::cout<

valueRoot["channel"] = valueNodeList;

std::cout<

进行如上的赋值操作之后,不能再调用valueNodeList访问数组,例如调用valueNodeList.size访问到的数据始终返回0,因为数据已经迁移到valueRoot对象中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值