jsoncpp 常用方法,json::value,reader,writer,

1. jsonCpp总所有对象、类名都在namespace json中,使用时只要包含json.h即可。

2. jsonCpp主要包含三种类型的class:valuereaderwrite

(1)Json::Value root; // 建立一个 json 对象

  • 新建key-value数据:

root["key1"] = Json::Value("value1"); // 新建一个 Key(名为:key1),赋予字符串值:"value1"。

root["key2"] = Json::Value(1); // 新建一个 Key(名为:key2),赋予数值:1。

root["key3"] = Json::Value(false); // 新建一个 Key(名为:key3),赋予bool值:false。

  • 获取类型:

Json::ValueType type = root.type(); //可获取 root 的类型。

  • 添加数组:类型数据

root["key_array"].append("string"); // 新建名为:key_array的key,对第一个元素赋值为字符串:"string"。

root["key_array"].append(22); // 为数组 key_array 赋值,对第二个元素赋值为:22。

(2)Json::Writer为纯虚类,并不能直接使用。需要使用其子类:Json::FastWriter(快,最常用)、Json::StyledWriter、Json::StyledStreamWriter。

  • Json::FastWriter file; //输出json数据

cout << file.write(root) << endl;

完整的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <json/json.h>


using namespace std;


int main()

{

Json::Value root;

root["key1"] = Json::Value("value1");

root["key2"] = Json::Value(1);

root["key3"] = Json::Value(false);

root["key_array"].append("string");

root["key_array"].append(22);



Json::FastWriter file;

cout << file.write(root) << endl;

}

输出结果为:

  • Json::StyledWriter file; //输出有格式的json数据

cout << file.write(root) << endl;

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <json/json.h>

using namespace std;


int main()

{

Json::Value root;

root["key1"] = Json::Value("value1");

root["key2"] = Json::Value(1);

root["key3"] = Json::Value(false);

root["key_array"].append("string");

root["key_array"].append(22);



Json::StyledWriter  file;

cout << file.write(root) << endl;

}

输出结果:

(3)Json::Reader 用于读取json数据的,

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <json/json.h>

#include <fstream>

using namespace std;

ifstream strJsonContent("jsontext.json", ios::binary);             //读取jsontext.json的json文件,strJsonContent也可以为str类型

Json::Reader reader;

Json::Value root;

if (reader.parse(strJsonContent, root))                           //解析strJsonContent文件

{

Json::Value::Members types = root.getMemberNames();            //得到子节点

for (Json::Value::Members::iterator it = types.begin(); it != types.end(); it++)     //遍历子节点

{

Json::Value versions = root[*it];

for (unsigned int i=0; i < versions.size(); i++) {

v.push_back(versions[i].asString());

}

}

return v;

}