C++要使用JSON来解析数据,一般采用jsoncpp.
网站:http://sourceforge.net/projects/jsoncpp/
下载了之后,解压,然后打开\jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\makefiles\vs71
下的工程文件,进行编译链接就可以得到一个静态链接库json.lib
要用jsoncpp只需要将这个lib文件拷贝到你的工程目录下,并将jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\include\json
复制到工程目录下,然后将这些头文件加到工程中去就可以了。
例子:
{
"name" : "小楼一夜听春雨",
"age" : 27
}
#pragma comment(lib, "json_mtd.lib") #include <fstream> #include <cassert> #include "json/json.h" int main() { ifstream ifs; ifs.open("testjson.json"); assert(ifs.is_open()); Json::Reader reader; Json::Value root; if (!reader.parse(ifs, root, false)) { return -1; } std::string name = root["name"].asString(); int age = root["age"].asInt(); std::cout<<name<<std::endl; std::cout<<age<<std::endl; return 0; }
[{"name" : "xiaoy", "age" :17} , {"name" : "xiaot", "age" : 20}]
#pragma comment(lib, "json_mtd.lib") #include <fstream> #include <cassert> #include "json/json.h" int main() { ifstream ifs; ifs.open("testjson.json"); assert(ifs.is_open()); Json::Reader reader; Json::Value root; if (!reader.parse(ifs, root, false)) { return -1; } std::string name; int age; int size = root.size(); for (int i=0; i<size; ++i) { name = root[i]["name"].asString(); age = root[i]["age"].asInt(); std::cout<<name<<" "<<age<<std::endl; } return 0; }
json写入:
#pragma comment(lib, "json_mtd.lib") #include <fstream> #include <cassert> #include "json/json.h" int main() { Json::Value root; Json::FastWriter writer; Json::Value person; person["name"] = "hello world"; person["age"] = 100; root.append(person); std::string json_file = writer.write(root); ofstream ofs; ofs.open("test1.json"); assert(ofs.is_open()); ofs<<json_file; return 0; }
结果:[{"age":100,"name":"hello world"}]
json对数组的解析还支持STL的风格。
Json::Value::Members member;//Members 这玩意就是vector<string>,typedef了而已 for (Json::Value::iterator itr = objArray.begin(); itr != objArray.end(); itr++) { member = (*itr).getMemberNames(); for (Json::Value::Members::iterator iter = member.begin(); iter != member.end(); iter++) { string str_temp = (*itr)[(*iter)].asString(); } }