RapidJSON的一些方便操作的宏定义

以前是一直使用CCJsonConventer去把JSON字符串转化为CCDictionary对象的,现在使用cocos2d-x 3.x后,不推荐使用CCDictionary了,而且,JSON库也换成了rapidjson,不过我暂时没找到好的封装,如果仅仅是用作数据提取的话,做几个宏定义就可以达到目的了。

/*
 * =====================================================================================
 *
 *       Filename:  RapidJsonMacro.h
 *
 *    Description:  Easy macro to operate RapidJSON
 *
 *        Version:  1.0
 *        Created:  12/26/2014 11:38:23
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Jason Tou (), [email protected]
 *   Organization:  
 *
 * =====================================================================================
 */

#pragma once

#include "json/rapidjson.h"
#include "json/document.h"

// 基础变量的校验
#define json_check_is_bool(value, strKey) (value.HasMember(strKey) && value[strKey].IsBool())
#define json_check_is_string(value, strKey) (value.HasMember(strKey) && value[strKey].IsString())
#define json_check_is_int32(value, strKey) (value.HasMember(strKey) && value[strKey].IsInt())
#define json_check_is_uint32(value, strKey) (value.HasMember(strKey) && value[strKey].IsUint())
#define json_check_is_int64(value, strKey) (value.HasMember(strKey) && value[strKey].IsInt64())
#define json_check_is_uint64(value, strKey) (value.HasMember(strKey) && value[strKey].IsUint64())
#define json_check_is_float(value, strKey) (value.HasMember(strKey) && value[strKey].IsFloat())
#define json_check_is_double(value, strKey) (value.HasMember(strKey) && value[strKey].IsDouble())

#define json_check_is_number(value, strKey) (value.HasMember(strKey) && value[strKey].IsNumber())
#define json_check_is_array(value, strKey) (value.HasMember(strKey) && value[strKey].IsArray())

// 得到对应类型的数据,如果数据不存在则得到一个默认值
#define json_check_bool(value, strKey) (json_check_is_bool(value, strKey) && value[strKey].GetBool())
#define json_check_string(value, strKey) (json_check_is_string(value, strKey) ? value[strKey].GetString() : "")
#define json_check_int32(value, strKey) (json_check_is_int32(value, strKey) ? value[strKey].GetInt() : 0)
#define json_check_uint32(value, strKey) (json_check_is_uint32(value, strKey) ? value[strKey].GetUint() : 0)
#define json_check_int64(value, strKey) (json_check_is_int64(value, strKey) ? ((value)[strKey]).GetInt64() : 0)
#define json_check_uint64(value, strKey) (json_check_is_uint64(value, strKey) ? ((value)[strKey]).GetUint64() : 0)
#define json_check_float(value, strKey) (json_check_is_float(value, strKey) ? ((value)[strKey]).GetFloat() : 0)
#define json_check_double(value, strKey) (json_check_is_double(value, strKey) ? ((value)[strKey]).GetDouble() : 0)

// 得到Value指针
#define json_check_value_ptr(value, strKey) (((value).HasMember(strKey)) ? &((value)[strKey]) : nullptr)

使用上也比较简单,比如获取一个字符串:

void getName(const rapidjson::Value& data)
{
    std::string strName = json_check_string(data, "name");
}
不过这里仅仅是罗列了只读数据的操作,写操作还没搞,貌似json数据在客户端还是解析的操作比较多,以后用到再总结吧

你可能感兴趣的:(cocos2dx)