1. 程式人生 > >C++使用Boost 解析Json

C++使用Boost 解析Json

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"}
   ]
}