#include <iostream>
#include <string>
#include "json/json.h"
#include "stdio.h"
int ReadJson(const std::string &);
std::string writeJson();
int main(int argc, char** argv)
{
using namespace std;
std::string strMsg;
cout<<"--------------------------------"<<endl;
strMsg = writeJson();
cout<< "json write : " << endl << strMsg << endl;
cout<<"--------------------------------"<<endl;
cout<< "json read :" << endl;
ReadJson(strMsg);
cout<<"--------------------------------"<<endl;
return 0;
}
int ReadJson(const std::string & strValue)
{
using namespace std;
Json::Reader reader;
Json::Value value;
if (reader.parse(strValue, value))
{
//解析json中的对象
string out = value["name"].asString();
cout << "name : " << out << endl;
cout << "number : " << value["number"].asInt() << endl;
cout << "value : " << value["value"].asBool() << endl;
cout << "no such num : " << value["haha"].asInt() << endl;
cout << "no such str : " << value["hehe"].asString() << endl;
//解析数组对象
const Json::Value arrayNum = value["arrnum"];
for (unsigned int i = 0; i < arrayNum.size(); i++)
{
cout << "arrnum[" << i << "] = " << arrayNum[i];
}
//解析对象数组对象
Json::Value arrayObj = value["array"];
cout << "array size = " << arrayObj.size() << endl;
for(unsigned int i = 0; i < arrayObj.size(); i++)
{
cout << arrayObj[i];
}
//从对象数组中找到想要的对象
for(unsigned int i = 0; i < arrayObj.size(); i++)
{
if (arrayObj[i].isMember("string"))
{
out = arrayObj[i]["string"].asString();
std::cout << "string : " << out << std::endl;
}
}
}
return 0;
}
std::string writeJson()
{
using namespace std;
Json::Value root;
Json::Value arrayObj;
Json::Value item;
Json::Value iNum;
item["string"] = "this is a string";
item["number"] = 999;
item["aaaaaa"] = "bbbbbb";
arrayObj.append(item);
item.clear();
item["heha"] = "hello";
arrayObj.append(item);
//直接对jsoncpp对象以数字索引作为下标进行赋值,则自动作为数组
iNum[1] = 1;
iNum[2] = 2;
iNum[3] = 3;
iNum[4] = 4;
iNum[5] = 5;
iNum[6] = 6;
//增加对象数组
root["array"] = arrayObj;
//增加字符串
root["name"] = "json";
//增加数字
root["number"] = 666;
//增加布尔变量
root["value"] = true;
//增加数字数组
root["arrnum"] = iNum;
root.toStyledString();
string out = root.toStyledString();
return out;
}
运行结果:
--------------------------------
json write :
{
"array" : [
{
"aaaaaa" : "bbbbbb",
"number" : 999,
"string" : "this is a string"
},
{
"heha" : "hello"
}
],
"arrnum" : [ null, 1, 2, 3, 4, 5, 6 ],
"name" : "json",
"number" : 666,
"value" : true
}
--------------------------------
json read :
name : json
number : 666
value : 1
no such num : 0
no such str :
arrnum[0] = nullarrnum[1] = 1arrnum[2] = 2arrnum[3] = 3arrnum[4] = 4arrnum[5] = 5arrnum[6] = 6array size = 2
{
"aaaaaa" : "bbbbbb",
"number" : 999,
"string" : "this is a string"
}{
"heha" : "hello"
}string : this is a string
--------------------------------