Cocos2d-x3.8.1解析Json文件

来源:互联网 发布:启动oracle数据库命令 编辑:程序博客网 时间:2024/05/21 18:13

//C++中有二十多种json解析库,根据各方面效率的对比,本文以rapidjson对json文件进行解析操作

//加入头文件以及命名空间

#include "cocos2d/external/json/allocators.h"
#include "cocos2d/external/json/document.h"
#include "cocos2d/external/json/stringbuffer.h"
#include "cocos2d/external/json/writer.h"

USING_NS_CC;


//rapidjson增,删,改,查操作

bool HelloWorld::init()
{

//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}


rapidjson::Document doc;
char name[32]="{\"name\":\"LiuJunLiang\"}";//转义


//解析字符串
doc.Parse<0>(name);

if (doc.HasParseError())//解析错误
{
log("parse error");
}
else//解析正确
{
log("parse true");
if (doc.HasMember("name")&&doc.IsObject())
{
//根据key获取value
rapidjson::Value& value=doc["name"];

if (value.IsString())
{
log("%s",value.GetString());
}


//设置value为int
value.SetInt(0);
if (value.IsInt())
{
log("%d",value.GetInt());
}
}


//添加数据
//获取分配器
rapidjson::Document::AllocatorType& allocator=doc.GetAllocator();

//添加int
doc.AddMember("year",19,allocator);


//添加string
doc.AddMember("cell","12345678910",allocator);


//添加null空对象
rapidjson::Value nullObj(rapidjson::kNullType);
doc.AddMember("null",nullObj,allocator);


//添加对象
rapidjson::Value birthday(rapidjson::kObjectType);
birthday.AddMember("year",1996,allocator);
birthday.AddMember("month",12,allocator);
birthday.AddMember("day",12,allocator);
doc.AddMember("birthday",birthday,allocator);


//添加数组
rapidjson::Value array(rapidjson::kArrayType);
array.PushBack(1,allocator);
array.PushBack("hellococos2d-x",allocator);
doc.AddMember("array",array,allocator);


//获取json全部内容
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);


log("json:%s",buffer.GetString());
}


return true;
}

0 0