jsoncpp 处理包含数组的JSON数据

前端之家收集整理的这篇文章主要介绍了jsoncpp 处理包含数组的JSON数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1 数据内容中有中括号[],表示里面是一个数组

{

"success" : false,

"toReturn" : [

{

"createTime" : "20080806114526000+0800",

"createUser" : "张三"

}

],

"total" : 1

}



代码


#include <iostream>

#include <fstream>

#include "json/json.h"

using namesapce std;

void ParseJsonText()

{

string strJsonText = "{\"total\":1,\"toReturn\":[{\"createTime\":\"20080806114526000+0800\",\"createUser\":\"张三\"}],\"success\":false}";

Json::Reader reader;

Json::Value value;

if (NULL == reader.parse(strJsonText,value)) return;


std::string strTotalNumber = value["total"].asString();

Json::Value subValue = value["toReturn"];

if (subValue.isNull()) return;


size_t count = subValue.size();

for (size_t i = 0; i < count; i++)

{

std::string strCreateTime = subValue[i]["createTime"].asString();

std::string strCreateUser = subValue[i]["createUser"].asString();

}

}


void StoreJsonTextToFile()

{

string strJsonText = "{\"total\":1,value)) return;


ofstream ofs;

ofs.open("storefile.json");

ofs << value.toStyledString() << endl;

ofs.close();

}


2 数据内容中内嵌一个子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"] = "fire alarm";

jsonParams["time_alarm"] = "2017-2-1 21:34:21";

jsonParams["alarm_source"] = "192.68.1.0";


jsonCode["params"] = jsonParams;

猜你在找的Json相关文章