jsoncpp添加对象、数组与json对象的解析
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
1、添加json的对象
Json::Value js;
js["method"] = "funcName";
js["ttl"] = "123";
js["Char"]["name"] = "hello";
std::string str = js.toStyledString();
上述的json对象如下:
{
"method":"funcName",
"ttl":"123",
"Char":
{
"name":"hello"
}
}
2、添加数组:
Json::Value js;
js["method"] = "funcName";
js["Char"]["name"] = "hello";
for(int i=0;i < 1;i++)
{
js["Char"]["pVtage"][i]["Value"]=true; //数组中插入对象
}
js["funN1"].resize(0); //插入空数据
js["FunN2"].append("123"); //插入数组
//json对象插入对json对象
Json::Value jsSub;
jsSub["greet"] = "hello";
jsSub["greet1"] = "world";
js["FunN2"].append(jsSub);
std::string str = js.toStyledString();
上述的json对象如下:
{
"method":"funcName",
"Char":
{
"name":"hello",
"pVtage":["Value":true]
},
"funN1":[],
"FunN2":[123],
[
{
“greet”:"hello",
"greet1":"world"
}
]
}
//插入空数组:
//添加数组
Json::Value jsTmp;
jsTmp["greet"] = "hello";
jsTmp["greet1"] = "world";
jsNew["FunN2"].append(Json::nullvalue).append(Json::Value(jsTmp));
//将json对象添加到其他Json对象中,需要使用Json::Value(obj)才可以保留待添加的json对象格式。若添加的格式处理不当,则待添加的对象格式失效,变为值"obj",
jsNew内容如下:
{
"FunN2":[
[
{
"greet":"hello",
"greet1":"world"
}
]
]
}
3、解析Json类型字符串:
char* pBuf = new char[1024*32];
Json::Value js;
if(Json::Reader().parse(pBuf,js))
{
//解析对象
int nValue = js["ttl"].asInt();
//解析数组
for(int i =0 ; i < js["pVtage"].size)
{
bool bValue = js["pVtage"][i]["Value"].asBool();
}
//其他类推
}
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
2 个月前
8c391e04
5 个月前
更多推荐
已为社区贡献4条内容
所有评论(0)