最近在使用json,由以前的jsoncpp转为rapidjson,听说这个效率高一点;
不过我觉得比较好的就是rapidjson不需要库,只要头文件就可以了
记录下来方便自己以后使用
#if 1 #include <string> #include <iostream> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> using namespace rapidjson; using namespace std; int main(int argc,char *argv[]) { Document document; document.SetObject(); Document::AllocatorType& allocator = document.GetAllocator(); Value array(kArrayType); for (int i = 0; i < 2; i++) { Value object(kObjectType); object.AddMember("id",1,allocator); object.AddMember("name","test",allocator); object.AddMember("version",1.01,allocator); object.AddMember("vip",true,allocator); array.PushBack(object,allocator); } document.AddMember("title","PLAYER INFO",allocator); document.AddMember("players",array,allocator); Value age(kArrayType); for (int j = 0; j < 5;j++) { Value object(kNumberType); object.SetInt(j); age.PushBack(object,allocator); } document.AddMember("age",age,allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); document.Accept(writer); const char * out = buffer.GetString(); cout << out << endl; cout << "-------------analyze--------------" << endl; /* { "title":"PLAYER INFO","players":[ { "id":1,"name":"test","version":1.01,"vip":true },{ "id":1,"vip":true } ],"age":[0,2,3,4] } */ Document doc1; doc1.Parse<0>(out); ///< 通过Parse方法将Json数据解析出来 if (doc1.HasParseError()) { cout << "GetParseError%s\n" << doc1.GetParseError() << endl; return 1; } rapidjson::Value & valString = doc1["title"]; if (valString.IsString()) { const char * str = valString.GetString(); cout << "title:"<<str << endl; } rapidjson::Value & valAge = doc1["age"]; if (valAge.IsArray()) { cout << "age:" << endl; for (int i = 0; i < valAge.Capacity(); ++i) { rapidjson::Value & val = valAge[i]; cout << val.GetInt() << endl; } } rapidjson::Value & players = doc1["players"]; if (players.IsArray()) { cout << "players:" << endl; for (int i = 0; i < players.Capacity(); ++i) { rapidjson::Value & val = players[i]; cout << "id:" << val["id"].GetInt() << endl; cout << "name:" << val["name"].GetString() << endl; cout << "version:" << val["version"].GetDouble() << endl; cout << "vip:" << val["vip"].GetBool() << endl; } } return 0; }