JsonCpp经典入门
1.JsonCpp1.1.JsonCpp简介JSON is a lightweight data-interchange format. It can represent numbers,strings,ordered sequences of values,and collections of name/value pairs. JsonCpp is a C++ library that allows manipulating JSON values,including serialization and deserialization to and from strings. It can also preserve existing comment in unserialization/serialization steps,making it a convenient format to store user input files. 1.2.JsonCpp环境搭建1.2.1.下载地址https://github.com/open-source-parsers/jsoncpp#generating-amalgamated-source-and-header 1.2.2.Qt中JsonCpp安装① 解压jsoncpp-master.zip包 1.3.读写JsonCpp1.3.1.写#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace Json;
using namespace std;
#if 0
{
"animals":{
"dog":[
{
"name":"Rufus","age":15
},{
"name":"Marty","age":null
}
]
}
}
#endif
void writeJson()
{
Value rootAnimalsObj;
Value dog;
Value dogArray;
Value dogValueItem1;
dogValueItem1["name"] = "Rufus";
dogValueItem1["age"] = 15;
Value dogValueItem2;
dogValueItem2["name"] = "Marty";
dogValueItem2["age"] = "";
dogArray.append(dogValueItem1);
dogArray.append(dogValueItem2);
dog["dog"] = dogArray;
rootAnimalsObj["animals"] = dog;
string str = rootAnimalsObj.toStyledString();
cout<<str;
ofstream ofs;
ofs.open("test_write.json");
ofs << str;
ofs.close();
return;
}
int main()
{
writeJson();
return 0;
}
1.3.2.读#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace Json;
using namespace std;
#if 0
{
"animals":{
"dog":[
{
"name":"Rufus","age":null
}
]
}
}
#endif
void readJson()
{
ifstream is("aa.json");
if(!is)
{
cout<<"open error"<<endl;
return;
}
Reader reader;
Value root;
if(reader.parse(is,root))
{
cout<<root<<endl;
Value & dogArr = root["animals"]["dog"];
for(int i=0; i<dogArr.size(); i++)
{
cout<<dogArr[i]["name"].asString()<<endl;
cout<<dogArr[i]["age"].asInt()<<endl;
}
}
is.close();
}
int main()
{
readJson();
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |