boost生成和解析json实例及定向到文件
添加boost:
1.点击还原NuGet包
1.
2.点击第一个安装
3. cpp代码中加载头文件即可
生成json
生成json
格式为:
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include<opencv2/opencv.hpp>
#include<vector>
using namespace std;
using namespace cv;
using namespace boost::property_tree;
int main() {
//ptree pt_1, pt_11, pt_12;
//pt_11.put("id", "3445");
//pt_11.put<int>("age", 29);
//pt_11.put("name", "chen");
//pt_12.push_back(make_pair("", pt_11));
//pt_12.push_back(make_pair("", pt_11));
//pt_12.push_back(make_pair("", pt_11));
replace or create child node "data"
//pt_1.put_child("data", pt_12);
//ostringstream os;
//write_json(os, pt_1);
//cout << os.str() << endl;
//system("pause");
//return 0;
vector<Point> points;
Point point1 = { 1,2 };
Point point2 = { 3,4 };
points.push_back(point1);
points.push_back(point2);
ptree pt_1, pt_12,pt_121,pt_1211, pt_122;
int a = 20;
pt_1.put<int>("code", a);
//pt_1.put("data", pt_12);
pt_121.put("url", "h");
pt_121.put<int>("people_num", 2);
pt_121.put<int>("is_high_density", 0);
//pt_122.put<int>("is_high_density", 0);
//pt_121.put<int>("x", points[0].x);
for (int i = 0; i < points.size(); i++) {
pt_1211.put<int>("x", points[i].x);
pt_1211.put<int>("y", points[i].y);
//pt_121.put("x","y", points[i]);
//pt_121.put<int>("y", points[i].y);
//cout << points[i].x;
//cout << points[i].y;
pt_122.push_back(make_pair("", pt_1211));
}
//pt_122.push_back(make_pair("", pt_1211));
//pt_122.push_back(make_pair("", pt_1211));
pt_121.put_child("people_point", pt_122);
pt_12.push_back(make_pair("", pt_121));
//pt_122.push_back(make_pair("", pt_1211));
pt_1.put_child("data", pt_12);
//pt_121.put_child("people_point", pt_122);
ostringstream os;
write_json(os, pt_1);
cout << os.str() << endl;
system("pause");
return 0;
}
运行截图:
已知 json 直接遍历所有:
加入exception: