boost json生成和解析用法

时间:2021-01-29 23:55:43

json c++库还是有很多的,因为工作上经常使用boost,这里选用boost的json,记录下用法。

举个栗子:

如果我们要生成如下格式的json:

{
"name":"jim",
"info":
{
"weight":"",
"all_phone":
[
{
"phone":""
},
{
"phone":""
}
]
}
}

解析和生成的示例代码如下

 #include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <vector>
using namespace boost::property_tree;
using namespace std;
bool CreateJson(wstring &wstr)
{
wstringstream wstream;
try
{
wptree pt;
pt.put(L"name",L"jim");
wptree info;
info.put(L"weight",L"");
wptree phone,phone_item1,phone_item2;
phone_item1.put(L"phone",L"");
phone_item2.put(L"phone",L"");
phone.push_back(make_pair(L"",phone_item1));
phone.push_back(make_pair(L"",phone_item2));
info.put_child(L"all_phone",phone);
pt.push_back(make_pair(L"info",info));
write_json(wstream,pt); }
catch(ptree_error pt)
{
pt.what();
return false;
}
wstr = wstream.str();
return true;
}
bool ParseJson(wstring &wstr)
{
try
{
wptree pt;
wstringstream wstream(wstr);
read_json(wstream,pt);
wstring wstrName = pt.get<wstring>(L"name");
wptree info = pt.get_child(L"info");
wstring weight = info.get<wstring>(L"weight");
int w=;
w=info.get<int>(L"weight");
wptree phones = info.get_child(L"all_phone");
vector<wstring>vcPhone;
BOOST_FOREACH(wptree::value_type &v,phones)
{
vcPhone.push_back(v.second.get<wstring>(L"phone"));
}
}
catch(ptree_error pt)
{
pt.what();
return false;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
wstring wstr;
CreateJson(wstr);
ParseJson(wstr);
return ;
}

用法还是很简单的

这里需要注意的是:

1 boost json不支持空数组,在本例中空数组对应的格式为"all_phone":"";

2  空的字符串字段转换为数字会抛异常。