• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            牽著老婆滿街逛

            嚴(yán)以律己,寬以待人. 三思而后行.
            GMail/GTalk: yanglinbo#google.com;
            MSN/Email: tx7do#yahoo.com.cn;
            QQ: 3 0 3 3 9 6 9 2 0 .

            使用jsoncpp封裝的Json序列化和反序列化的工具類

            C++序列化和反序列化json需要寫的代碼實(shí)在是太多了,太過于臃腫了.
            相比較其他的語言,如:js,php等.如果在其他語言里面用過json,再在c++里面來使用,那種感覺會是非常無奈的,而且抗拒的.
            怎么說呢,勉強(qiáng)的還是能用的吧.湊合用吧.

            JsonSerializer.h
            /**********************************************************************
            * 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();

                /// 刷新成風(fēng)格化的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:
                /// 當(dāng)開關(guān)打開的時(shí)候,所有的數(shù)據(jù)序列化為數(shù)組.
                void toArray() { bToArray = true; }

                /// 當(dāng)開關(guān)打開的時(shí)候,序列化的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;        ///< 序列化成數(shù)組

                std::vector<uint8>    zipBuffer;

                int                    readPos;        ///< 數(shù)組讀取索引
                int                    writePos;        ///< 數(shù)組寫入索引
            };


            #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

            JsonSerializer.cpp
            /**********************************************************************
            * 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")
            #endif

            JsonSerializer::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;
            }

            測試1
            struct TestData1 : public JsonSerializer
            {
                time_t        nServerTime;

                TestData1()
                {
                    clear();
                }

                void clear()
                {
                    nServerTime = 0;
                }

                /// 序列化
                virtual const char* serialized()
                {
                    clearBuffer();
                    append(_T("time"), nServerTime);
                    return flush();
                }

                /// 反序列化
                virtual bool deserialize(const char* str, size_t size)
                {
                    if (str != NULL && size != 0)
                    {
                        if (!parse(str, size)) return false;
                    }

                    read(_T("time"), nServerTime);

                    return true;
                }
            };

            void test1()
            {
                // 序列化
                TestData1 data1;
                data1.nServerTime = time(0);
                data1.serialized();
                OUTPUT_STYLE_JSON(data1);

                // 反序列化
                TestData1 data2;
                std::string strJson = "{\"time\" : 1481207292 }";
                data2.deserialize(strJson.c_str(), strJson.length());
                printf("time :%d\n", data2.nServerTime);
            }

            測試2
            struct TestData2 : public JsonSerializer
            {
                time_t        nServerTime;
                std::vector<int32> arrInt;
                std::string strTest;

                TestData2()
                {
                    clear();
                }

                void clear()
                {
                    nServerTime = 0;
                    arrInt.clear();
                    strTest.clear();
                }

                /// 序列化
                virtual const char* serialized()
                {
                    clearBuffer();
                    append(_T("time"), nServerTime);
                    append(_T("ints"), arrInt);
                    append(_T("str"), strTest);
                    return flush();
                }

                /// 反序列化
                virtual bool deserialize(const char* str, size_t size)
                {
                    if (str != NULL && size != 0)
                    {
                        if (!parse(str, size)) return false;
                    }

                    read(_T("time"), nServerTime);
                    read(_T("ints"), arrInt);
                    read(_T("str"), strTest);

                    return true;
                }
            };

            void test2()
            {
                // 序列化
                TestData2 data1;
                data1.nServerTime = time(0);
                data1.arrInt.push_back(1);
                data1.arrInt.push_back(2);
                data1.arrInt.push_back(3);
                data1.arrInt.push_back(4);
                data1.strTest = "序列化字符串";

                data1.serialized();
                OUTPUT_STYLE_JSON(data1);
            }

            測試執(zhí)行兩個測試的結(jié)果大概如下:


            注意:
            1.依賴zlib,在第三方庫里面拷貝zlib1d.dll到bin目錄;
            2.jsoncpp的lib我嫌太大了,就刪掉了,需要自行編譯.


            完整代碼下載
            /Files/tx7do/testJsonSerializer.zip

            posted on 2016-12-08 22:49 楊粼波 閱讀(2179) 評論(0)  編輯 收藏 引用


            只有注冊用戶登錄后才能發(fā)表評論。
            網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問   Chat2DB   管理


            久久人人爽人人人人爽AV| 国产精品久久久久9999高清| 久久亚洲国产精品成人AV秋霞| 久久精品国产99久久久古代| 丰满少妇人妻久久久久久| 91亚洲国产成人久久精品网址| 一97日本道伊人久久综合影院| 久久久久久国产精品免费无码| 久久久久97国产精华液好用吗| 久久午夜福利无码1000合集| 色成年激情久久综合| 亚洲中文字幕久久精品无码APP| 四虎国产精品免费久久久| 久久久久国产精品嫩草影院| 久久成人永久免费播放| 97久久综合精品久久久综合| 精品无码久久久久国产动漫3d| 国产AV影片久久久久久| 国产综合久久久久久鬼色| 波多野结衣久久| 无码任你躁久久久久久| 国产精品成人无码久久久久久| 久久精品99久久香蕉国产色戒 | 99久久久精品免费观看国产| 伊人久久大香线蕉综合网站| 久久精品成人影院| 久久青草国产手机看片福利盒子| 中文无码久久精品| 久久久久久精品无码人妻| 亚洲国产成人精品女人久久久 | 国产精久久一区二区三区| 777米奇久久最新地址| 久久久亚洲欧洲日产国码二区 | 国产农村妇女毛片精品久久| 久久久精品午夜免费不卡| 午夜精品久久久久久中宇| 囯产极品美女高潮无套久久久| 囯产精品久久久久久久久蜜桃 | 无遮挡粉嫩小泬久久久久久久| 久久久久亚洲AV成人网人人网站 | 国产2021久久精品|