一、json格式简介
先看一个例子:
value 可为字符串、数字、集合,以及集合构成的数组。
先看一个例子:
{
"陕西": [
{ "编号":1, "城市": "西安", "电话区号":"029", "邮政编码": "710000" },
{ "编号":2, "城市": "汉中", "电话区号":"0916 ", "邮政编码": "723000" },
],
"四川": [
{ "编号":3, "城市": "成都", "电话区号":"028", "邮政编码": "610000" },
{ "编号":4, "城市": "绵阳", "电话区号":"0816 ", "邮政编码": "621000" },
{ "编号":5, "城市": "自贡", "电话区号":"0813", "邮政编码": "643000" }
],
"广东": [
{ "编号":6, "城市": "广州", "电话区号":"020", "邮政编码": "510000" },
{ "编号":7, "城市": "深圳", "电话区号":"0755 ", "邮政编码": "518000" },
{ "编号":8, "城市": "珠海", "电话区号":"0756", "邮政编码": "519000" }
]
}
json 数据格式中,最小单元是由格式为 {"key":value} 组成的键值对,多组键值对的可放在一个 {} 里用逗号隔开形成集合;value 可为字符串、数字、集合,以及集合构成的数组。
接下来我们照着这个例子来构造和解析。
二、构造
这里用的是c++ boost库,完整代码在后面。
//1
std::vector<std::pair<std::string, int> > number;
for(std::size_t i = 0; i < 8; ++i)
{
std::pair<std::string, int> num("Number", i+1);
number.push_back(num);
}
std::pair<std::string, std::string> city1("City", "Xi'an");
std::pair<std::string, std::string> city2("City", "Hanzhong");
std::pair<std::string, std::string> city3("City", "Chengdu");
std::pair<std::string, std::string> city4("City", "Mianyang");
std::pair<std::string, std::string> city5("City", "Zigong");
std::pair<std::string, std::string> city6("City", "Guangzhou");
std::pair<std::string, std::string> city7("City", "Shenzhen");
std::pair<std::string, std::string> city8("City", "Zhuhai");
std::pair<std::string, std::string> areacode1("The area code", "029");
std::pair<std::string, std::string> areacode2("The area code", "0916");
std::pair<std::string, std::string> areacode3("The area code", "028");
std::pair<std::string, std::string> areacode4("The area code", "0816");
std::pair<std::string, std::string> areacode5("The area code", "0813");
std::pair<std::string, std::string> areacode6("The area code", "020");
std::pair<std::string, std::string> areacode7("The area code", "0755");
std::pair<std::string, std::string> areacode8("The area code", "0756");
std::pair<std::string, std::string> postalcode1("Postalcode", "710000");
std::pair<std::string, std::string> postalcode2("Postalcode", "723000");
std::pair<std::string, std::string> postalcode3("Postalcode", "610000");
std::pair<std::string, std::string> postalcode4("Postalcode", "621000");
std::pair<std::string, std::string> postalcode5("Postalcode", "643000");
std::pair<std::string, std::string> postalcode6("Postalcode", "510000");
std::pair<std::string, std::string> postalcode7("Postalcode", "518000");
std::pair<std::string, std::string> postalcode8("Postalcode", "519000");
为了清楚,写的有些繁琐。2、做一个 {"城市": "西安"} 文件
//2
boost::pro