1. 交叉编译链接:
linux编译jsoncpp_linux交叉编译jsoncpp_我是谁??的博客-CSDN博客
2. json格式的解析
json文件包含内容如下,需要解析出zhangsan及其同学的信息;
{
"name":"zhangsan",
"age":18,
"score":{
"math":"prefect",
"english":90
},
"classmate":[
{
"name":"lisi",
"age":19,
"score":{
"math":"good",
"english":120
}
},
{
"name":"wanger",
"age":17,
"score":{
"math":"nice",
"english":88
}
}
]
}
利用
jsoncpp解析
上述json内容的c++代码如下:
Json::Value json_value;
Json::Reader json_reader;
ifstream infile("./info.json",ios::binary);
if(infile.is_open()){
if(json_reader.parse(infile, json_value)){
std::string ZSName = json_value["name"].asString();
Json::Int ZSAge = json_value["age"].asInt();
std::string ZSMath = json_value["score"]["math"].asString();
Json::Int ZSEng = json_value["score"]["english"].asInt();
std::cout << "Name:" << ZSName << " Age:"<<ZSAge
<< " math:" << ZSMath << " eng:" << ZSEng << endl;
Json::Value classMate = json_value["classmate"];
printf("classMate size = %d \n",classMate.size());
for(int i = 0; i < classMate.size(); ++i){
std::cout << "Name:" << classMate[i]["name"].asString()
<< " Age:"<<classMate[i]["age"].asInt()
<< " math:" << classMate[i]["score"]["math"].asString()
<< " eng:" << classMate[i]["score"]["english"].asInt()
<< endl;
}
}else{
printf("parse failed \n");
}
infile.close();
}
/*运行结果:
Name:zhangsan Age:18 math:prefect eng:90
classMate size = 2
Name:lisi Age:19 math:good eng:120
Name:wanger Age:17 math:nice eng:88
*/
/*
举一反三:多层结构写法类似
*/
3. 打包为json格式
//打包
Json::Value json_value;
json_value["name"] = Json::Value("zhangsan");
json_value["age"] = Json::Value(18);
Json::Value score;
score["math"] = Json::Value("prefect");
score["english"] = Json::Value(90);
json_value["score"] = score;
Json::Value classmateArr;
//打包lisi信息
Json::Value classmateLi;
classmateLi["name"] = Json::Value("lisi");
classmateLi["age"] = Json::Value(19);
Json::Value classmateScoreLi;
classmateScoreLi["math"] = Json::Value("good");
classmateScoreLi["english"] = Json::Value(120);
classmateLi["score"] = classmateScoreLi;
//打包wanger信息
Json::Value classmateWang;
classmateWang["name"] = Json::Value("wanger");
classmateWang["age"] = Json::Value(17);
Json::Value classmateScoreWang;
classmateScoreWang["math"] = Json::Value("nice");
classmateScoreWang["english"] = Json::Value(88);
classmateWang["score"] = classmateScoreWang;
//加入数组
classmateArr.append(classmateLi);
classmateArr.append(classmateWang);
//将数组加入主体
json_value["classmate"] = classmateArr;
//写入文件
Json::FastWriter writer;
const std::string json_file = writer.write(json_value);
ofstream outfile("/mnt/mount/photo/writeInfo.json",ios::binary);
outfile.write(json_file.c_str(), json_file.length());
outfile.close();
/*
内容和上面一样,只是排版是横向的;
*/
版权声明:本文为qq_39048131原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。