C++序列化和反序列化json需要写的代码实在是太多了,太过于臃肿了.
相比较其他的语言,如:js,php等.如果在其他语言里面用过json,再在c++里面来使用,那种感觉会是非常无奈的,而且抗拒的.
怎么说呢,勉强的还是能用的吧.凑合用吧.
/**********************************************************************
* Copyright (C) 2015 - tx7do - All Rights Reserved
*
* 文件名称: JsonSerializer.h
* 摘 要: Json序列化工具
*
* 作 者: yanglinbo,
* 修 改: 查看文件最下方.
*
***********************************************************************/#ifndef __JsonSerializer_H__
#define __JsonSerializer_H__
#include <assert.h>
#include <vector>
#include <json/json.h>
typedef signed __int8 int8;
typedef unsigned __int8 uint8;
typedef signed __int16 int16;
typedef unsigned __int16 uint16;
typedef signed __int32 int32;
typedef unsigned __int32 uint32;
typedef signed __int64 int64;
typedef unsigned __int64 uint64;
class JsonSerializer
{
public:
JsonSerializer();
virtual~JsonSerializer();
JsonSerializer&
operator=(
const JsonSerializer& other)
{
return *
this;
}
public:
/// 序列化
virtual const char* serialized() = 0;
/// 反序列化
virtual bool deserialize(
const char* data, size_t size) = 0;
public:
/// 清除缓存
void clearBuffer();
void resetReadPos() { readPos = 0; }
void resetWritePos() { writePos = 0; }
void resetPosition() { resetReadPos(); resetWritePos(); }
/// 刷新json字符串
const char* flush();
/// 刷新成风格化的json字符串
const std::
string& style_flush();
/// 是否具有该键
bool isKeyValid(
const std::
string& key)
const;
bool isKeyValid(
const char* key)
const;
/// 获取json字符串
const std::
string& getString()
const {
return document; }
public:
/// 当开关打开的时候,所有的数据序列化为数组.
void toArray() { bToArray =
true; }
/// 当开关打开的时候,序列化的json字符串将被zip压缩.解序列化之前,将会被zip解压缩.
void enableZip() { bEnableZip =
true; }
public:
void append(
const std::
string& key,
const int8& value);
void append(
const std::
string& key,
const int16& value);
void append(
const std::
string& key,
const int32& value);
void append(
const std::
string& key,
const int64& value);
void append(
const std::
string& key,
const uint8& value);
void append(
const std::
string& key,
const uint16& value);
void append(
const std::
string& key,
const uint32& value);
void append(
const std::
string& key,
const uint64& value);
///
void append(
const std::
string& key,
const float& value);
#ifdef _VECTOR_
template <typename T>
void append(
const std::
string& key,
const std::vector<T>& value)
{
Json::Value arrayObj;
if (!value.empty())
{
typename std::vector<T>::const_iterator iter = value.begin();
typename std::vector<T>::const_iterator& iEnd = value.end();
for (; iter != iEnd; ++iter)
{
arrayObj.append( *iter );
}
}
else {
arrayObj.resize(0);
}
if (bToArray || key.empty())
{
root.append(arrayObj);
}
else {
root[key] = arrayObj;
}
if (bFlushNow) flush();
}
template <typename T>
void appendEx(
const std::
string& key, std::vector<T>& value)
{
Json::Value arrayObj;
if (!value.empty())
{
typename std::vector<T>::iterator iter = value.begin();
typename std::vector<T>::iterator& iEnd = value.end();
for (; iter != iEnd; ++iter)
{
T& current_value = *iter;
current_value.clearBuffer();
current_value.serialized();
arrayObj.append( current_value.root );
}
}
else {
arrayObj.resize(0);
}
if (bToArray || key.empty())
{
root.append(arrayObj);
}
else {
root[key] = arrayObj;
}
if (bFlushNow) flush();
}
template <typename V>
bool read(
const std::
string& key, std::vector<V>& value)
{
Json::Value& arrayObj = bToArray ? root[readPos++] : root[key];
value.clear();
Json::Value::iterator iter = arrayObj.begin();
Json::Value::iterator iEnd = arrayObj.end();
for (; iter!=iEnd; ++iter)
{
value.push_back(readValue(*iter, V()));
}
return true;
}
template <typename V>
bool readEx(
const std::
string& key, std::vector<V>& value)
{
Json::Value& arrayObj = bToArray ? root[readPos++] : root[key];
value.clear();
V vObj;
Json::Value::iterator iter = arrayObj.begin();
Json::Value::iterator iEnd = arrayObj.end();
for (; iter!=iEnd; ++iter)
{
Json::Value& current_value = *iter;
vObj.clearBuffer();
vObj.root = current_value;
vObj.deserialize(NULL, 0);
value.push_back(vObj);
}
return true;
}
#endif#ifdef _LIST_
template <typename T>
void append(
const std::
string& key,
const std::list<T>& value)
{
Json::Value arrayObj;
if (!value.empty())
{
typename std::list<T>::const_iterator iter = value.begin();
typename std::list<T>::const_iterator& iEnd = value.end();
for (; iter != iEnd; ++iter)
{
arrayObj.append(*iter);
}
}
else {
arrayObj.resize(0);
}
if (bToArray || key.empty())
{
root.append(arrayObj);
}
else {
root[key] = arrayObj;
}
if (bFlushNow) flush();
}
template <typename V>
bool read(
const std::
string& key, std::list<V>& value)
{
Json::Value& arrayObj = bToArray ? root[readPos++] : root[key];
value.clear();
Json::Value::const_iterator iter = arrayObj.begin();
Json::Value::const_iterator iEnd = arrayObj.end();
for (; iter!=iEnd; ++iter)
{
value.push_back(read(*iter));
}
}
#endif#ifdef _MAP_
template <typename K, typename V>
void append(
const std::
string& key,
const std::map<K, V>& value)
{
Json::Value arrayObj;
typename std::map<K, V>::const_iterator iter = value.begin();
typename std::map<K, V>::const_iterator& iEnd = value.end();
for (; iter != iEnd; ++iter)
{
arrayObj[iter->first] = (iter->second);
}
if (bToArray || key.empty())
{
root.append(arrayObj);
}
else {
root[key] = arrayObj;
}
if (bFlushNow) flush();
}
template <typename K, typename V>
bool read(
const std::
string& key, std::map<K, V>& value)
{
Json::Value arrayObj = root[key];
value.clear();
}
#endif#ifdef _XSTRING_
void append(
const std::
string& key,
const std::
string& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
#endif void append(
const std::
string& key, JsonSerializer& value);
public:
bool parse(
const char* str, size_t size);
bool read(
const std::
string& key,
bool& value);
bool read(
const std::
string& key, int8& value);
int8 readValue(
const Json::Value& v, int8 def=0)
const;
bool read(
const std::
string& key, int16& value);
int16 readValue(
const Json::Value& v, int16 def=0)
const;
bool read(
const std::
string& key, int32& value);
int32 readValue(
const Json::Value& v, int32 def=0)
const;
bool read(
const std::
string& key, int64& value);
int64 readValue(
const Json::Value& v, int64 def=0)
const;
bool read(
const std::
string& key, uint8& value);
uint8 readValue(
const Json::Value& v, uint8 def=0)
const;
bool read(
const std::
string& key, uint16& value);
uint16 readValue(
const Json::Value& v, uint16 def=0)
const;
bool read(
const std::
string& key, uint32& value);
uint32 readValue(
const Json::Value& v, uint32 def=0)
const;
bool read(
const std::
string& key, uint64& value);
uint64 readValue(
const Json::Value& v, uint64 def=0)
const;
bool read(
const std::
string& key,
float& value);
float readValue(
const Json::Value& v,
float def=0)
const;
bool read(
const std::
string& key,
char* value);
#ifdef _XSTRING_
bool read(
const std::
string& key, std::
string& value)
{
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asCString();
return true;
}
std::
string readValue(
const Json::Value& v, std::
string def="")
const {
try {
return v.asCString();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
#endif bool read(
const std::
string& key, time_t& value);
template <typename T>
void readObj(
const std::
string& key, T& value)
{
Json::Value& obj = (bToArray || key.empty()) ? root[readPos++] : root[key];
value.root = obj;
value.deserialize();
}
private:
size_t get_temp_buffer_size(
const size_t src_length);
public:
Json::FastWriter writer;
Json::Reader reader;
Json::Value root;
std::
string document;
///< json字符串
bool bFlushNow;
///< 立即刷新json字符串
bool bEnableZip; ///< 将json字符串压缩/解压缩成zip格式
bool bToArray; ///< 序列化成数组
std::vector<uint8> zipBuffer;
int readPos;
///< 数组读取索引
int writePos; ///< 数组写入索引
};
#define OUTPUT_JSON_LEN(MSG) printf("字符串长度:%d\n", MSG.getString().length());
#define OUTPUT_STYLE_JSON(MSG) printf(MSG.style_flush().c_str());
#define OUTPUT_JSON(MSG) printf(MSG.getString().c_str());
#define TEST_SERIALIZE(MSG) MSG.serialized(); OUTPUT_JSON_LEN(MSG); OUTPUT_STYLE_JSON(MSG);
#endif /**********************************************************************
* Copyright (C) 2015 - tx7do - All Rights Reserved
*
* 文件名称: JsonSerializer.cpp
* 摘 要: Json序列化工具
*
* 作 者: yanglinbo,
* 修 改: 查看文件最下方.
*
***********************************************************************/#include "Stdafx.h"
#include "JsonSerializer.h"
#include <json/json.h>
#include <zip.h>
#include <unzip.h>
#ifdef _DEBUG
# pragma comment(lib, "json_vc71_libmtd.lib")
# pragma comment(lib, "zlib1d.lib")
#else# pragma comment(lib, "json_vc71_libmt.lib")
# pragma comment(lib, "zlib1.lib")
#endifJsonSerializer::JsonSerializer() : bFlushNow(
false)
, bEnableZip(
false)
, bToArray(
false)
, readPos(0)
, writePos(0)
{
//writer = new Json::FastWriter;
//reader = new Json::Reader;
//root = new Json::Value;
}
JsonSerializer::~JsonSerializer()
{
//safe_delete(writer);
//safe_delete(reader);
//safe_delete(root);
}
void JsonSerializer::clearBuffer()
{
root.clear();
flush();
document.clear();
resetPosition();
}
const char* JsonSerializer::flush()
{
document.clear();
document = writer.write(root);
if (bEnableZip)
{
if (zipBuffer.size() < document.length())
{
zipBuffer.resize(document.length());
}
uLong comprLen = (uLong) zipBuffer.size();
int err = compress(&zipBuffer[0], &comprLen, (
const Bytef*)document.c_str(), (uLong)document.length());
//TRACE("压缩长度:%d\n", comprLen);
document.assign((
const char*)&zipBuffer[0], comprLen);
}
return document.c_str();
}
const std::
string& JsonSerializer::style_flush()
{
flush();
Json::StyledWriter style_writer;
Json::Reader style_reader;
style_reader.parse( document, root );
document = style_writer.write( root );
return document;
}
bool JsonSerializer::isKeyValid(
const std::
string& key)
const{
return !root[key].isNull();
}
bool JsonSerializer::isKeyValid(
const char* key)
const{
return !root[key].isNull();
}
void JsonSerializer::append(
const std::
string& key,
const int8& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const int16& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const int32& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const int64& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const uint8& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const uint16& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const uint32& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const uint64& value)
{
if (bToArray || key.empty())
{
root.append(value);
}
else {
root[key] = value;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key,
const float& value)
{
char buffer[64] = {0};
#if _MSC_VER > 1310
int result = _snprintf_s(buffer,
sizeof (buffer), "%.2f", value);
#else int result = _snprintf(buffer,
sizeof (buffer), "%.2f", value);
#endif if (result==
sizeof(buffer) || result<0)
{
buffer[
sizeof(buffer)-1] = 0;
}
if (bToArray || key.empty())
{
root.append(buffer);
}
else {
root[key] = buffer;
}
if (bFlushNow) flush();
}
void JsonSerializer::append(
const std::
string& key, JsonSerializer& value)
{
value.serialized();
if (bToArray || key.empty())
{
root.append(value.root);
}
else {
root[key] = value.root;
}
if (bFlushNow) flush();
}
bool JsonSerializer::parse(
const char* str, size_t size)
{
if (bEnableZip)
{
uLong uncomprLen = (uLong)get_temp_buffer_size(size + 1);
if (zipBuffer.size() < uncomprLen)
{
zipBuffer.resize(uncomprLen);
}
Byte* uncompr = &zipBuffer[0];
ZeroMemory(uncompr, uncomprLen);
int err = uncompress(uncompr, &uncomprLen, (
const Byte*)str, (uLong)size);
str = (
const char*) uncompr;
size = uncomprLen;
}
if (!reader.parse(str, str+size, root,
false))
{
std::
string strError = reader.getFormatedErrorMessages();
TRACE("解析错误:[%s]\n", strError.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key,
bool& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asBool();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, int8& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, int16& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, int32& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, int64& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asInt64();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, uint8& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asUInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, uint16& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asUInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, uint32& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asUInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, uint64& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asUInt64();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key,
float& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
if (v.isString())
{
const char* str = 0;
str = v.asCString();
if (str == NULL)
return false;
char temp = 0;
#if _MSC_VER > 1310
sscanf_s(str, " %g", &value, &temp);
#else sscanf(str, " %g", &value, &temp);
#endif return true;
}
else if (v.isDouble())
{
value = v.asFloat();
return true;
}
else if (v.isInt())
{
value = (
float) v.asInt();
}
else if (v.isUInt())
{
value = (
float) v.asUInt();
}
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, TCHAR* value)
{
if (value == NULL)
return false;
try {
const char* str = NULL;
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
str = v.asCString();
if (str == NULL)
return false;
strncpy(value, str, strlen(str));
//value[str.length()+1] = '\0';.
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
bool JsonSerializer::read(
const std::
string& key, time_t& value)
{
try {
Json::Value& v = (bToArray || key.empty()) ? root[readPos++] : root[key];
if (v.isNull())
return false;
value = v.asInt();
}
catch (std::exception& e)
{
TRACE("[%s]Json读取异常: %s.\n", key.c_str(), e.what());
return false;
}
catch (
)
{
TRACE("[%s]Json读取未知异常.\n", key.c_str());
return false;
}
return true;
}
size_t JsonSerializer::get_temp_buffer_size(
const size_t src_length)
{
const size_t MB = 1024 * 1024;
if (src_length < 1*MB)
{
return 1*MB;
}
else if ((src_length >= 1*MB) && (src_length < 8*MB))
{
return 8*MB;
}
else {
return 16*MB;
}
}
int8 JsonSerializer::readValue(
const Json::Value& v, int8 def
/*=0*/)
const{
try {
return v.asInt();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
int16 JsonSerializer::readValue(
const Json::Value& v, int16 def
/*=0*/)
const{
try {
return v.asInt();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
int32 JsonSerializer::readValue(
const Json::Value& v, int32 def
/*=0*/)
const{
try {
return v.asInt();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
int64 JsonSerializer::readValue(
const Json::Value& v, int64 def
/*=0*/)
const{
try {
return v.asInt64();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
uint8 JsonSerializer::readValue(
const Json::Value& v, uint8 def
/*=0*/)
const{
try {
return v.asUInt();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
uint16 JsonSerializer::readValue(
const Json::Value& v, uint16 def
/*=0*/)
const{
try {
return v.asUInt();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
uint32 JsonSerializer::readValue(
const Json::Value& v, uint32 def
/*=0*/)
const{
try {
return v.asUInt();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
uint64 JsonSerializer::readValue(
const Json::Value& v, uint64 def
/*=0*/)
const{
try {
return v.asUInt64();
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}
float JsonSerializer::readValue(
const Json::Value& v,
float def
/*=0*/)
const{
try {
float value = 0;
if (v.isString())
{
const char* str = 0;
str = v.asCString();
if (str == NULL)
return false;
char temp = 0;
#if _MSC_VER > 1310
sscanf_s(str, " %g", &value, &temp);
#else sscanf(str, " %g", &value, &temp);
#endif return value;
}
else if (v.isNumeric())
{
value = v.asFloat();
return value;
}
}
catch (
)
{
TRACE("Json读取未知异常.\n");
return def;
}
return def;
}