1.下载Boost库。
2.建立控制台项目。
3.配置Boost路径。
项目属性 - C/C++ - 常规 - 附加包含目录 - 添加Boost库的路径。
4.代码实例
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include<string>
using namespace boost::property_tree;
using namespace std;
//解析Json
bool ParseJson()
{
string str = "{\"ID\":0,\"Student\":[{\"Name\":\"April\"},{\"Name\":\"Harris\"}]}";
stringstream stream(str);
ptree strTree;
try {
read_json(stream, strTree);
}
catch (ptree_error & e) {
return false;
}
try {
int id = strTree.get<int>("ID");
ptree names = strTree.get_child("Student");
BOOST_FOREACH(ptree::value_type &name, names)
{
stringstream s;
write_json(s, name.second);
string image_item = s.str();
}
}
catch (ptree_error & e)
{
return false;
}
return true;
}
//构造Json
bool InsertJson()
{
string str = "{\"ID\":0,\"Student\":[{\"Name\":\"April\"},{\"Name\":\"Harris\"}]}";
stringstream stream(str);
ptree strTree;
try {
read_json(stream, strTree);
}
catch (ptree_error & e) {
return false;
}
ptree subject_info;
ptree array1, array2, array3;
array1.put("course", "Java");
array2.put("course", "C++");
array3.put("course", "MySql");
subject_info.push_back(make_pair("", array1));
subject_info.push_back(make_pair("", array2));
subject_info.push_back(make_pair("", array3));
strTree.put_child("Subject", subject_info);
stringstream s;
write_json(s, strTree);
string outstr = s.str();
return true;
}
int main()
{
ParseJson();
InsertJson();
system("pause");
return 0;
}
待解析的Json数据如下:
{
"ID": 0,
"Student":
[
{"Name": "April"},
{"Name": "Harris"}
]
}
重建后的Json数据如下:
{
"ID": 0,
"Student":
[
{ "Name": "April"},
{ "Name": "Harris"}
],
"Subject":
[
{"course": "Java"},
{"course": "C++"},
{"course": "MySql"}
]
}
版权声明:本文为liyazhen2011原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。