什么是JSON
{
key:value,
key:value,
...
key:value
}
{ "firstName":"John" , "lastName":"Doe" }
[JsonObj, JsonObj ...JsonObj]
{"country":"China", "history":"5000年", "people":"14亿", "province":"34个省份", "supercity":[{"城市":"上海","地域":"华东","人口":"2100万","外号":"魔都"}, {"城市":"北京","地域":"华北","人口":"2300万","外号":"帝都"}, {"城市":"广州","地域":"华南","人口":"1600万","外号":"魔都"}]}
Json::Value supercity = china["supercity"]; int nSize = supercity.size(); for (int i = 0; i < nSize; ++i) { Json::Value city = supercity[i]; }
void WriteJsonFile() { Json::Value china, supercity, shanghai,beijing,guangzhou; //设置china相关数据 china["country"] = "China"; china["people"] = "14亿"; china["history"] = "5000年"; china["province"] = "34个省份"; //设置上海数据 shanghai["城市"] = "上海"; shanghai["人口"] = "2100万"; shanghai["外号"] = "魔都"; shanghai["地域"] = "华东"; //设置北京数据 beijing["城市"] = "北京"; beijing["人口"] = "2300万"; beijing["外号"] = "帝都"; beijing["地域"] = "华北"; //设置广州数据 guangzhou["城市"] = "广州"; guangzhou["人口"] = "1600万"; guangzhou["外号"] = "魔都"; guangzhou["地域"] = "华南"; //将上海、北京、广州添加到超级大城市数组中 supercity.append(shanghai); supercity.append(beijing); supercity.append(guangzhou); //将supercity添加到china对象中 china["supercity"] = supercity; //将Json数据写入到文件中 Json::StyledWriter writer; std::string strChina = writer.write(china); std::ofstream ofs; ofs.open("china.json"); if (ofs.is_open()) { ofs<<strChina; //将字符串写入到文件中 } }
读Json文件
void ReadJsonFileAndParse() { std::ifstream ifs; ifs.open("china.json"); if (!ifs.is_open()) return; Json::Value china; Json::Reader reader; reader.parse(ifs, china); //输出china中的对象 printf("country:%s\n", china["country"]); printf("people:%s\n", china["people"]); printf("history:%\ns", china["history"]); printf("province:%s\n", china["province"]); //获取supercitye数组 Json::Value supercity = china["supercity"]; int nSize = supercity.size(); //获取supercity数组大小 //遍历数组 for (int i = 0; i < nSize; ++i) { Json::Value city = supercity[i]; //根据索引获取supercity中的Json子对象 printf("城市:%s\n", supercity[i]["城市"]); printf("人口:%s\n", supercity[i]["人口"]); printf("外号:%s\n", supercity[i]["外号"]); printf("地域:%s\n", supercity[i]["地域"]); } }
参考资料:http://www.cnblogs.com/kex1n/archive/2011/12/02/2272328.html
http://baike.baidu.com/view/136475.htm?fr=aladdin
http://www.cppfans.org/1445.html