使用jsoncpp读写JSON

还可以用另一个库 nlohmann

从Github上下载后,使用老三步安装:

1
2
3
4
mkdir dir && cd dir
cmake ..
make
sudo make install

安装的路径如下:

在CMakeList里进行配置,别忘了最后链接库文件:-ljsoncpp

写JSON

1
2
3
4
5
6
7
Json::Value ret_json;

ret_json["msg"] = "Hello JSON";
ret_json["code"] = 123;
ret_json["ret"] = true;

cout << ret_json.toStyledString()<< endl;

运行结果:

1
2
3
4
5
{
"code" : 123,
"msg" : "Hello JSON",
"ret" : true
}

写JSON数组如下:

1
2
3
4
5
6
7
8
9
10
Json::Value ret_json,sub;
sub.append(Json::Value(123));
sub.append(Json::Value(456));
sub.append(Json::Value(789));

ret_json["msg"] = "Hello JSON";
ret_json["code"] = sub;
ret_json["ret"] = true;

cout << ret_json.toStyledString()<< endl;

结果为:

1
2
3
4
5
{
"code" : [ 123, 456, 789 ],
"msg" : "Hello JSON",
"ret" : true
}