版本cocos2d-x2.1.3json
今天作一個項目要用到json解析,遇到一點問題,浪費了一下午的時間,如今記錄下來,以避免遺忘。spa
使用的是cocos2d-x自帶的json解析類,只能解析不能生成,新建一個項目,首先作兩個準備(我就是忘了作,浪費一下午時間),第1、點擊新建的項目右鍵->屬性code
第二個在附加依賴項中添加libExtensions.lib、blog
而後代碼部分就簡單了.h文件中添加get
#include "cocos2d.h" #include "spine\Json.h" #include "cocos-ext.h" USING_NS_CC_EXT; USING_NS_CC;
.cpp文件中添加string
AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); const char* text= "{\"record\":{\"data\":20130101,\"rate\":23,\"buy\":1},\"record\":{\"data\":45,\"rate\":67,\"buy\":1},\"record\":{\"data\":45,\"rate\":76,\"buy\":10}}"; Json* root= cocos2d::extension::Json_create(text); Json* _record=root->child; while(_record) { Json* _date=cocos2d::extension::Json_getItem(_record, "data"); if(_date->type==Json_Number) { int date= _date->valueint; CCLOG("Date: %d",date); } Json* _rate=Json_getItem(_record, "rate"); if(_rate->type==Json_Number) { int rate=_rate->valueint; CCLOG("Rate: %d",rate); } Json* _buy=Json_getItem(_record, "buy"); if(_buy->type==Json_Number) { int buy=_buy->valueint; CCLOG("Buy: %d",buy); } _record=_record->next; } cocos2d::extension::Json_dispose(root);
這樣一個最簡單的json解析就行了io
json不在同級的.cpp文件class
char* text="{\"status\":10,\"body\":{\"force\":5,\"latest\":{\"ver\":\"2.0\",\"ver_num\":\"200\"}}}"; Json*root=Json_create(text); Json*_status=Json_getItem(root,"status"); if(_status->type==Json_Number){ int status=_status->valueint; CCLOG("status : %d",status); } Json*_body=Json_getItem(root,"body"); if(_body->type==Json_Object){ Json*_force=Json_getItem(_body,"force"); if(_force->type==Json_Number){ int force=_force->valueint; CCLOG("force : %d",force); } Json*_latest=Json_getItem(_body,"latest"); if(_latest->type==Json_Object){ Json*_ver=Json_getItem(_latest,"ver"); if(_ver->type==Json_String){ const char*ver=_ver->valuestring; CCLOG("ver : %s",ver); } Json*_ver_num=Json_getItem(_latest,"ver_num"); if(_ver_num->type==Json_String){ const char *ver_num=_ver_num->valuestring; CCLOG("ver_num : %s",ver_num); } } }