cocos2d-x json解析
版本cocos2d-x2.1.3
今天做一个项目要用到json解析,遇到一点问题,浪费了一下午的时间,现在记录下来,以免遗忘。
使用的是cocos2d-x自带的json解析类,只能解析不能生成,新建一个项目,首先做两个准备(我就是忘了做,浪费一下午时间),第一、点击新建的项目右键->属性
第二个在附加依赖项中添加libExtensions.lib、
然后代码部分就简单了.h文件中添加
#include "cocos2d.h" #include "spine\Json.h" #include "cocos-ext.h" USING_NS_CC_EXT; USING_NS_CC;
.cpp文件中添加
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解析就好了
json不在同级的.cpp文件
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); } } }