Cocos2d-x 3.0 加入了rapidjson庫用於json解析。位於external/json下。json
rapidjson 項目地址:http://code.google.com/p/rapidjson/ wiki:http://code.google.com/p/rapidjson/wiki/UserGuideapi
下面就經過實例代碼講解rapidjson的用法。ide
引入頭文件ui
#include "json/rapidjson.h" #include "json/document.h"
json解析google
std::string str = "{\"hello\" : \"word\"}"; CCLOG("%s\n", str.c_str()); rapidjson::Document d; d.Parse<0>(str.c_str()); if (d.HasParseError()) //打印解析錯誤 { CCLOG("GetParseError %s\n",d.GetParseError()); } if (d.IsObject() && d.HasMember("hello")) { CCLOG("%s\n", d["hello"].GetString());//打印獲取hello的值 }
打印結果spa
cocos2d: {"hello" : "word"} cocos2d: word
注意:只支持標準的json格式,一些非標準的json格式不支持。code
一些經常使用的解析方法須要本身封裝。注意判斷解析節點是否存在。get
引入頭文件string
#include "json/document.h" #include "json/writer.h" #include "json/stringbuffer.h" using namespace rapidjson;
生成json串it
rapidjson::Document document; document.SetObject(); rapidjson::Document::AllocatorType& allocator = document.GetAllocator(); rapidjson::Value array(rapidjson::kArrayType); rapidjson::Value object(rapidjson::kObjectType); object.AddMember("int", 1, allocator); object.AddMember("double", 1.0, allocator); object.AddMember("bool", true, allocator); object.AddMember("hello", "你好", allocator); array.PushBack(object, allocator); document.AddMember("json", "json string", allocator); document.AddMember("array", array, allocator); StringBuffer buffer; rapidjson::Writer<StringBuffer> writer(buffer); document.Accept(writer); CCLOG("%s",buffer.GetString());
打印結果
cocos2d: {"json":"json string","array":[{"int":1,"double":1,"bool":true,"hello":"你好"}]}