json c++庫仍是有不少的,由於工做上常用boost,這裏選用boost的json,記錄下用法。c++
舉個栗子:json
若是咱們要生成以下格式的json:數組
{ "name":"jim", "info": { "weight":"50", "all_phone": [ { "phone":"123" }, { "phone":"123" } ] } }
解析和生成的示例代碼以下spa
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 }
用法仍是很簡單的code
這裏須要注意的是:blog
1 boost json不支持空數組,在本例中空數組對應的格式爲"all_phone":"";字符串
2 空的字符串字段轉換爲數字會拋異常。get