boost json生成和解析用法

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

举个栗子:

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

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

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

 1 #include <boost/property_tree/ptree.hpp>
 2 #include <boost/property_tree/json_parser.hpp>
 3 #include <boost/foreach.hpp>
 4 #include <vector>
 5 using namespace boost::property_tree;
 6 using namespace std;
 7 bool CreateJson(wstring &wstr)
 8 {
 9     wstringstream wstream;
10     try
11     {
12         wptree pt;
13         pt.put(L"name",L"jim");
14         wptree info;
15         info.put(L"weight",L"50");
16         wptree phone,phone_item1,phone_item2;
17         phone_item1.put(L"phone",L"123");
18         phone_item2.put(L"phone",L"123");
19         phone.push_back(make_pair(L"",phone_item1));
20         phone.push_back(make_pair(L"",phone_item2));
21         info.put_child(L"all_phone",phone);
22         pt.push_back(make_pair(L"info",info));
23         write_json(wstream,pt);
24 
25     }
26     catch(ptree_error pt)
27     {
28       pt.what();
29       return false;
30     }
31     wstr = wstream.str();
32     return true;
33 }
34 bool ParseJson(wstring &wstr)
35 {
36     try
37     {
38         wptree pt;
39         wstringstream wstream(wstr);
40         read_json(wstream,pt);
41         wstring wstrName = pt.get<wstring>(L"name");
42         wptree info = pt.get_child(L"info");
43         wstring weight = info.get<wstring>(L"weight");
44         int w=0;
45         w=info.get<int>(L"weight");
46         wptree phones = info.get_child(L"all_phone");
47         vector<wstring>vcPhone;
48         BOOST_FOREACH(wptree::value_type &v,phones)
49         {
50             vcPhone.push_back(v.second.get<wstring>(L"phone"));
51         }
52     }
53     catch(ptree_error pt)
54     {
55         pt.what();
56         return false;
57     }
58     return true;
59 }
60 int _tmain(int argc, _TCHAR* argv[])
61 {
62     wstring wstr;
63     CreateJson(wstr);
64     ParseJson(wstr);
65     return 0;
66 }

 用法还是很简单的

这里需要注意的是:

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

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

原文地址:https://www.cnblogs.com/doutu/p/4874336.html