Boost教程(四)读写JSON

Boost读写JSON用的是property_tree模块,这个模块不用加到find_package里,它没有库文件,直接include头文件即可.但用法总体上不如Qt的JSON模块好用。

今天发现用Boost写JSON有个大问题,就是数值类型和bool最终都被转化为字符串,无法避免。所以最好不要用Boost读写JSON了

写JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

const std::string file_path="/home/user/test.txt";

boost::property_tree::ptree root;
boost::property_tree::ptree items;

boost::property_tree::ptree item1;
item1.put("ID","1");
item1.put("Name","wang");
items.push_back(std::make_pair("1",item1));

boost::property_tree::ptree item2;
item2.put("ID","2");
item2.put("Name","zhang");
items.push_back(std::make_pair("2",item2));

root.put_child("user",items);
boost::property_tree::write_json(file_path,root);

这样写出的JSON如下:

1
2
3
4
5
6
7
{
"user": {
"1": { "ID": "1","Name": "wang"},
"2": { "ID": "2","Name": "zhang"},
"3": { "ID": "3", "Name": "li"}
}
}

把最后两句改一下:

1
boost::property_tree::write_json(file_path,item1);

结果如下:
1
2
3
4
{
"ID": "1",
"Name": "wang"
}

把最后两句再这样改:

1
2
root.put_child("user",item1);
boost::property_tree::write_json(file_path,root);

结果如下:
1
2
3
4
5
6
{
"user": {
"ID": "1",
"Name": "wang"
}
}

修改某个JSON值

1
2
3
4
json::ptree pt;
pt.put("data",1);
pt.put("num",2);
pt.get_child("num").put_value(9);

JSON数组

实现JSON数组还是只用ptree类型,稍微复杂点,之前因为make_pair而一直以为用别的方法,其实是让paire的key为空即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace json = boost::property_tree;

json::ptree pt;
json::ptree children;
json::ptree child1, child2, child3;

child1.put("", 1);
child2.put("", 2);
child3.put("", 3);

children.push_back(std::make_pair("", child1));
children.push_back(std::make_pair("", child2));
children.push_back(std::make_pair("", child3));

pt.add_child("MyArray", children);

std::stringstream stream;
json::write_json(stream, pt);
cout<< stream.str() <<endl;

运行结果:
1
2
3
4
5
6
7
{
"MyArray": [
"1",
"2",
"3"
]
}

同样结果,代码还可以优化成这样:

1
2
3
4
5
6
json::ptree child;
for(int i=0;i<3;i++)
{
child.put("", i);
children.push_back(std::make_pair("", child));
}

child的内容会依次更新,逐个都插入children

将json写入string

1
2
3
std::stringstream stream;
boost::property_tree::write_json(stream, item1);
cout<<stream.str()<<endl;

不能直接用cout<<,没有重载运算符,不过这样也比较简单

从string中解析json串

1
2
3
4
5
6
7
8
// json是 { "a": 2}
std::string c; //c为json串
std::istringstream iss;
iss.str(c);

boost::property_tree::ptree item;
boost::property_tree::json_parser::read_json(iss, item);
int n = item.get<int>("a");