C++对Json数据的友好处理实现过程

目录
  • 背景
  • 设计
    • 目标:
    • 效果:
  • 实现
    • 基本数据类型转换
    • 自定义数据结构类型
    • 成员变量处理
    • 成员变量注册
    • 模板匹配防止编译报错
    • 成员变量匹配Key重命名
    • Object2Json实现
  • 亮点
  • 源码
  • 参考文档
  • 总结

背景

C/C++客户端需要接收和发送JSON格式的数据到后端以实现通讯和数据交互。C++没有现成的处理JSON格式数据的接口,直接引用第三方库还是避免不了拆解拼接。考虑到此项目将会有大量JSON数据需要处理,避免不了重复性的拆分拼接。所以打算封装一套C++结构体对象转JSON数据、JSON数据直接装C++结构体对象的接口,类似于数据传输中常见的序列化和反序列化,以方便后续处理数据,提高开发效率。

设计

目标:

  • 通过简单接口就能将C++结构体对象实例转换为JSON字符串数据,或将一串JSON字符串数据加载赋值到一个C++结构体对象实例。理想接口:Json2Object(inJsonString, outStructObject),或者Object2Json(inStructObject, outJsonString)
  • 支持内置基本类型如bool,int,double的Json转换,支持自定义结构体的Json转换,支持上述类型作为元素数组的Json转换,以及支持嵌套的结构体的Json转换

效果:

先上单元测试代码

TEST_CASE("解析结构体数组到JSON串", "[json]")
{
    struct DemoChildrenObject
    {
        bool boolValue;
        int intValue;
        std::string strValue;
        /*JSON相互转换成员变量声明(必需)*/
        JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)
    };

    struct DemoObjct
    {
        bool boolValue;
        int intValue;
        std::string strValue;
        /*嵌套的支持JSON转换的结构体成员变量,数组形式*/
        std::vector< DemoChildrenObject> children;

        /*JSON相互转换成员变量声明(必需)*/
        JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue, children)
    };

    DemoObjct demoObj;
    /*开始对demoObj对象的成员变量进行赋值*/
    demoObj.boolValue = true;
    demoObj.intValue = 321;
    demoObj.strValue = "hello worLd";

    DemoChildrenObject child1;
    child1.boolValue = true;
    child1.intValue = 1000;
    child1.strValue = "hello worLd child1";

    DemoChildrenObject child2;
    child2.boolValue = true;
    child2.intValue = 30005;
    child2.strValue = "hello worLd child2";

    demoObj.children.push_back(child1);
    demoObj.children.push_back(child2);
    /*结束对demoObj对象的成员变量的赋值*/

    std::string jsonStr;
    /*关键转换函数*/
    REQUIRE(Object2Json(jsonStr, demoObj));
    std::cout << "returned json format: " << jsonStr << std::endl;

    /*打印的内容如下:
    returned json format: {
       "boolValue" : true,
       "children" : [
          {
             "boolValue" : true,
             "intValue" : 1000,
             "strValue" : "hello worLd child1"
          },
          {
             "boolValue" : true,
             "intValue" : 30005,
             "strValue" : "hello worLd child2"
          }
       ],
       "intValue" : 321,
       "strValue" : "hello worLd"
    }
    */

    DemoObjct demoObj2;
    /*关键转换函数*/
    REQUIRE(Json2Object(demoObj2, jsonStr));

    /*校验转换后的结构体变量中各成员变量的内容是否如预期*/
    REQUIRE(demoObj2.boolValue == true);
    REQUIRE(demoObj2.intValue == 321);
    REQUIRE(demoObj2.strValue == "hello worLd");

    REQUIRE(demoObj2.children.size() == 2);

    REQUIRE(demoObj.children[0].boolValue == true);
    REQUIRE(demoObj.children[0].intValue == 1000);
    REQUIRE(demoObj.children[0].strValue == "hello worLd child1");

    REQUIRE(demoObj.children[1].boolValue == true);
    REQUIRE(demoObj.children[1].intValue == 30005);
    REQUIRE(demoObj.children[1].strValue == "hello worLd child2");
}

实现

本次我们只关注怎么友好地在结构体与Json字符串之间进行转换,而不深入关注JSon字符串具体如何与基本数据类型进行转换。这个已经有不少的第三方库帮我们解决这个问题,如cJSONJsoncpprapidjson,不必再重复造轮子。

此次我们选择了JsonCPP作为底层的JSON解析支持,如果想替换成其他三方库也比较简单,修改对应嵌入的内容即可。

我们的目标是实现两个接口:

  • Json2Object(inJsonString, outStructObject)
  • Object2Json(inStructObject, outJsonString)

结合JsonCPP自身定义的类型,我们进一步需要实现的是:

  • Json2Object(const Json::Value& jsonTypeValue, outStructObject)
  • Object2Json(inStructObject, const std::string& key, Json::Value& jsonTypeValue)

基本数据类型转换

对于如bool、int、double、string等基本数据类型,该实现均较为简单:

/*int 类型支持*/
static bool Json2Object(int& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isInt()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asInt();
        return true;
    }
}

static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const int& value)
{
    jsonTypeValue[key] = value;
    return true;
}

/*std::string 字符串类型支持*/
static bool Json2Object(std::string& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asString();
        return true;
    }
}

static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const std::string& value)
{
    jsonTypeValue[key] = value;
    return true;
}

自定义数据结构类型

对于自定义的结构体类型,我们要做的就是要保证其成员变量能够与JSON节点一一对应,并能够匹配进行数据填充。

   /*Json字符串:
   {
   "boolValue" : true,
   "intValue" : 1234,
   "strValue" : "demo object!"
   }*/

   struct DemoObjct
    {
        bool boolValue;
        int intValue;
        std::string strValue;
    };

如上面示例,在相互转换过程中,"boolValue"能与DemoObjct对象中名为boolValue的成员变量对应,"strValue"与DemoObjct对象中名为strValue的成员变量对应。

正常情况下,对于这种场景,我们只能对DemoObjct结构体额外实现处理函数进行数据转换,因不同的结构体声明定义的成员变量都不一样,所以针对每个结构体均需要单独实现,工作繁琐,不通用。

从这里下手,我们要做的就是“隐藏”针对类结构体实现的转换函数,利用语言自身的特性(函数模板等)让他们帮我们去做这些事情。

  • 声明转换成员函数,在这个成员函数实现里,让每个成员变量能从JSON原生数据中读取或写入值。
  • 注册成员变量,目的是让转换成员函数知道需要处理哪些成员变量,每个成员变量又对应JSON原生数据中的哪个节点字段,以便匹配读写。
  • 在外部调用Json2Object 和Object2Json函数时,触发调用该转换成员函数,以便填充或输出成员变量的内容。

把大象装进冰箱里只需要三步,我们来看这三步怎么走。

成员变量处理

  • 考虑到每个结构体的成员变量类型和数量不可控,并且需要将每个成员变量作为左值(Json2Object时),不能简单采用数组枚举方式处理,可以采用C++11的特性——可变参数模板,从里到外遍历处理每个成员变量
template <typename T>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg)
{
    const auto key = names[index];
    if (!jsonTypeValue.isMember(key) || Json2Object(arg, jsonTypeValue[key])) {
        return true;
    } else {
        return false;
    }
}

template <typename T, typename... Args>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg, Args&... args)
{
    if (!JsonParse(names, index, jsonTypeValue, arg)) {
        return false;
    } else {
        return JsonParse(names, index + 1, jsonTypeValue, args...);
    }
}
  • 成员变量与JSON原生节点key字段有对应关系,初步先简单考虑,将成员变量名称先视为JSON中对应节点的key名称。这个可以通过宏定义的特性实现,将声明注册的成员变量内容作为字符串拆分出key名称列表。
#define JSONCONVERT2OBJECT_MEMEBER_REGISTER(...)  \
bool ParseHelpImpl(const Json::Value& jsonTypeValue)
{
    std::vector<std::string> names = Member2KeyParseWithStr(#__VA_ARGS__);
    return JsonParse(names, 0, jsonTypeValue, __VA_ARGS__);
}

成员变量注册

例如DemoObjct这个类结构体,添加JSONCONVERT2OBJECT_MEMEBER_REGISTER并带上成员变量的注册声明:

   struct DemoObjct
    {
        bool boolValue;
        int intValue;
        std::string strValue;

       JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)

    };

等同于:

   struct DemoObjct
    {
        bool boolValue;
        int intValue;
        std::string strValue;

       bool ParseHelpImpl(const Json::Value& jsonTypeValue,
                          std::vector<std::string> &names)
        {
            names = Member2KeyParseWithStr("boolValue, intValue, strValue");
            //names 得到 ["boolValue","intValue", "strValue"]
            //然后带着这些key逐一从Json中取值赋值到成员变量中
            return JsonParse(names, 0, jsonTypeValue, boolValue, intValue, strValue);
        }
    };

模板匹配防止编译报错

到目前为止,核心的功能已经实现。如果目标结构体类未添加JSON转换的声明注册,外部在使用Json2Object接口时会导致编译报错,提示找不到ParseHelpImpl这个成员函数的声明定义……,我们可以采用enable_if来给未声明注册宏的结构体提供缺省函数。

template <typename TClass, typename enable_if<HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
    std::vector<std::string> names = PreGetCustomMemberNameIfExists(aimObj);
    return aimObj.JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeValue, names);
}

template <typename TClass, typename  enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
    return false;
}

成员变量匹配Key重命名

目前的实现均为将成员变量的名称作为JSON串中的Key名称,为灵活处理,再补充一个宏用于重新声明结构体成员变量中对应到JSON串中的key,例如:

    struct DemoObjct
    {
        bool boolValue;
        int intValue;
        std::string strValue;

        JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)
        /*重新声明成员变量对应到JSON串的key,注意顺序一致*/
        JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER("bValue", "iValue", "sValue")
    };

    DemoObjct demoObj;
    /*boolValue <--> bValue; intValue <--> iValue; ...*/
    REQUIRE(Json2Object(demoObj, std::string("{\"bValue\":true, \"iValue\":1234, \"sValue\":\"demo object!\"}")));
    REQUIRE(demoObj.boolValue == true);
    REQUIRE(demoObj.intValue == 1234);
    REQUIRE(demoObj.strValue == "demo object!");

Object2Json实现

上面提到为大多为实现Json2Object接口所提供的操作,从结构体对象转成Json也是类似的操作,这里就不再阐述,详细可参考源码。

亮点

  • 简化C++对JSON数据的处理,屏蔽注意拆分处理JSON数据的操作;
  • 提供简易接口,从结构体到JSON串、JSON串转结构体切换自如

源码

#include "json/json.h"
#include <string>
#include <vector>
#include <initializer_list>

#define JSONCONVERT2OBJECT_MEMEBER_REGISTER(...)  \
bool JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(const Json::Value& jsonTypeValue, std::vector<std::string> &names) \
{     \
    if(names.size() <= 0)  { \
        names = Member2KeyParseWithStr(#__VA_ARGS__); \
    }   \
    return JsonParse(names, 0, jsonTypeValue, __VA_ARGS__); \
}   \
bool OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(Json::Value& jsonTypeValue, std::vector<std::string> &names) const \
{     \
    if(names.size() <= 0)  { \
        names = Member2KeyParseWithStr(#__VA_ARGS__); \
    }   \
    return ParseJson(names, 0, jsonTypeValue, __VA_ARGS__); \
}   \

#define JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER(...)  \
std::vector<std::string> JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE() const \
{     \
    return Member2KeyParseWithMultiParam({ __VA_ARGS__ }); \
}

namespace JSON
{
template <bool, class TYPE = void>
struct enable_if
{
};

template <class TYPE>
struct enable_if<true, TYPE>
{
    typedef TYPE type;
};
} //JSON

template <typename T>
struct HasConverFunction
{
    template <typename TT>
    static char func(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE)); //@1

    template <typename TT>
    static int func(...); //@2

    const static bool has = (sizeof(func<T>(NULL)) == sizeof(char));

    template <typename TT>
    static char func2(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE)); //@1
    template <typename TT>
    static int func2(...); //@2
    const static bool has2 = (sizeof(func2<T>(NULL)) == sizeof(char));
};

static std::vector<std::string> Member2KeyParseWithMultiParam(std::initializer_list<std::string> il)
{
    std::vector<std::string> result;
    for (auto it = il.begin(); it != il.end(); it++) {
        result.push_back(*it);
    }
    return result;
}

inline static std::string NormalStringTrim(std::string const& str)
{
    static char const* whitespaceChars = "\n\r\t ";
    std::string::size_type start = str.find_first_not_of(whitespaceChars);
    std::string::size_type end = str.find_last_not_of(whitespaceChars);
    return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
}

inline static std::vector<std::string> NormalStringSplit(std::string str, char splitElem)
{
    std::vector<std::string> strs;
    std::string::size_type pos1, pos2;
    pos2 = str.find(splitElem);
    pos1 = 0;
    while (std::string::npos != pos2) {
        strs.push_back(str.substr(pos1, pos2 - pos1));
        pos1 = pos2 + 1;
        pos2 = str.find(splitElem, pos1);
    }
    strs.push_back(str.substr(pos1));
    return strs;
}

static std::vector<std::string> Member2KeyParseWithStr(const std::string& values)
{
    std::vector<std::string> result;
    auto enumValues = NormalStringSplit(values, ',');
    result.reserve(enumValues.size());
    for (auto const& enumValue : enumValues) {
        result.push_back(NormalStringTrim(enumValue));
    }
    return result;
}

//////////////////////////////////////////////////////////////////////////////

static bool Json2Object(bool& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isBool()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asBool();
        return true;
    }
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, bool value)
{
    jsonTypeValue[key] = value;
    return true;
}

static bool Json2Object(int& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isInt()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asInt();
        return true;
    }
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const int& value)
{
    jsonTypeValue[key] = value;
    return true;
}

static bool Json2Object(unsigned int& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isUInt()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asUInt();
        return true;
    }
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const unsigned int& value)
{
    jsonTypeValue[key] = value;
    return true;
}

static bool Json2Object(double& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isDouble()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asDouble();
        return true;
    }
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const double& value)
{
    jsonTypeValue[key] = value;
    return true;
}

static bool Json2Object(std::string& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
        return false;
    } else {
        aimObj = jsonTypeValue.asString();
        return true;
    }
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const std::string& value)
{
    jsonTypeValue[key] = value;
    return true;
}

template <typename TClass, typename JSON::enable_if<HasConverFunction<TClass>::has2, int>::type = 0>
static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
{
    return aimObj.JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE();
}

template <typename TClass, typename JSON::enable_if<!HasConverFunction<TClass>::has2, int>::type = 0>
static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
{
    return std::vector<std::string>();
}

template <typename TClass, typename JSON::enable_if<HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
    std::vector<std::string> names = PreGetCustomMemberNameIfExists(aimObj);
    return aimObj.JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeValue, names);
}

template <typename TClass, typename JSON::enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
    return false;
}

template <typename T>
static bool Json2Object(std::vector<T>& aimObj, const Json::Value& jsonTypeValue)
{
    if (jsonTypeValue.isNull() || !jsonTypeValue.isArray()) {
        return false;
    } else {
        aimObj.clear();
        bool result(true);
        for (int i = 0; i < jsonTypeValue.size(); ++i) {
            T item;
            if (!Json2Object(item, jsonTypeValue[i])) {
                result = false;
            }
            aimObj.push_back(item);
        }
        return result;
    }
}

template <typename T>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg)
{
    const auto key = names[index];
    if (!jsonTypeValue.isMember(key) || Json2Object(arg, jsonTypeValue[key])) {
        return true;
    } else {
        return false;
    }
}

template <typename T, typename... Args>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg, Args&... args)
{
    if (!JsonParse(names, index, jsonTypeValue, arg)) {
        return false;
    } else {
        return JsonParse(names, index + 1, jsonTypeValue, args...);
    }
}

/** Provider interface*/
template<typename TClass>
bool Json2Object(TClass& aimObj, const std::string& jsonTypeStr)
{
    Json::Reader reader;
    Json::Value root;

    if (!reader.parse(jsonTypeStr, root) || root.isNull()) {
        return false;
    }
    return Json2Object(aimObj, root);
}

static bool GetJsonRootObject(Json::Value& root, const std::string& jsonTypeStr)
{
    Json::Reader reader;
    if (!reader.parse(jsonTypeStr, root)) {
        return false;
    }
    return true;
}

////////////////////////////////////////////////////////////////////////

template <typename TClass, typename JSON::enable_if<HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
{
    std::vector<std::string> names = PreGetCustomMemberNameIfExists(objValue);
    if (key.empty()) {
        return objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeOutValue, names);
    } else {
        Json::Value jsonTypeNewValue;
        const bool result = objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeNewValue, names);
        if (result) {
            jsonTypeOutValue[key] = jsonTypeNewValue;
        }
        return result;
    }
}

template <typename TClass, typename JSON::enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
{
    return false;
}

template <typename T>
static bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const std::vector<T>& objValue)
{
    bool result(true);
    for (int i = 0; i < objValue.size(); ++i) {
        Json::Value item;
        if (!Object2Json(item, "", objValue[i])) {
            result = false;
        } else {
            if (key.empty()) jsonTypeOutValue.append(item);
            else jsonTypeOutValue[key].append(item);
        }
     }
    return result;
}

template <typename T>
static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, const T& arg)
{
    if (names.size() > index) {
        const std::string key = names[index];
        return Object2Json(jsonTypeValue, key, arg);
    } else {
        return false;
    }
}

template <typename T, typename... Args>
static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, T& arg, Args&... args)
{
    if (names.size() - (index + 0) != 1 + sizeof...(Args)) {
        return false;
    }
    const std::string key = names[index];
    Object2Json(jsonTypeValue, key, arg);

    return ParseJson(names, index + 1, jsonTypeValue, args...);
}

/** Provider interface*/
template<typename T>
bool Object2Json(std::string& jsonTypeStr, const T& obj)
{
    //std::function<Json::Value()>placehoder = [&]()->Json::Value { return Json::Value(); };
    //auto func = [&](std::function<Json::Value()>f) { return f(); };
    //Json::Value val = func(placehoder);

    Json::StyledWriter writer;
    Json::Value root;
    const bool result = Object2Json(root, "", obj);
    if (result) {
        jsonTypeStr = writer.write(root);
    }
    return result;
}

参考文档

  • C++类结构体与json相互转换
  • C++ 轻量级对象JSON序列化实现

总结

到此这篇关于C++对Json数据的友好处理的文章就介绍到这了,更多相关C++对Json数据的处理内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++中结构体和Json字符串互转的问题详解

    大家有没有在项目中遇到过,将一些预定义的本地结构体转换为Json字符串后,发送到网络中的情形.那我猜想下大家常规的做法:写一个函数,传入结构体的指针,然后在函数中对结构体的每一个成员根据其类型,使用Json类库的赋值方法,直接或间接创建Json子对象,组成一个内存树状结构,最后调用Json类库的方法生成字符串.这样的做法似乎比较完美,工作完成得很好,确实也挑不出什么毛病来,让我们先看看在golang中是怎么做的: type Person struct { Name string Age int

  • C++解析Json的方法详解【jsoncpp】

    本文实例讲述了C++解析Json的方法.分享给大家供大家参考,具体如下: JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似,本文主要对VS2008中使用Jsoncpp解析json的方法做一下记录. Jsoncpp是个跨平台的开源库,下载地址:http://sourceforge.net/projects/jsoncpp/,我下载的是v0.5.0,压缩包大约104K. 方法一:使用Jsoncpp生成的lib文件 解压上面下载的Jsoncpp

  • C++构造和解析Json的使用示例

    概述 JSON是一种轻量级的数据交互格式,易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率,实际项目中经常用到,相比xml有很多优点,问问度娘,优点一箩筐. 第三方库 json解析选用jsoncpp作为第三方库,jsoncpp使用广泛,c++开发首选. jsoncpp目前已经托管到了github上,地址:https://github.com/open-source-parsers/jsoncpp 使用 使用c++进行构造json和解析json,选用vs2010作为IDE.工程

  • 详解C++的JSON静态链接库JsonCpp的使用方法

    JsonCpp部署方法: 在http://sourceforge.net/projects/jsoncpp/中下载最新版本的jsoncpp库源码. 之后将jsoncpp-src-版本号-tar.gz解压出来,打开makefiles中的jsoncpp.sln进行编译,之后build文件夹下的vs71\debug\lib_json中会有一个.lib静态链接库. JsonCpp主要包含三种类型的class:Value Reader Writer. jsoncpp中所有对象.类名都在namespace

  • C++使用jsoncpp解析json的方法示例

    前言: 曾经一段时间XML成为互联网业界内的数据传输格式标准,但有人对XML提出了质疑,认为XML数据格式比较繁杂,冗长等,于是提出了一种新的表示格式-JSON. 对于JSON格式,在此就不作详细的说明了,下面主要讨论下C++解析json文件的工具-Jsoncpp的使用. JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似,本文主要对VS2008中使用Jsoncpp解析json的方法做一下记录. Jsoncpp是个跨平台的开源库,下载地址:

  • C++对Json数据的友好处理实现过程

    目录 背景 设计 目标: 效果: 实现 基本数据类型转换 自定义数据结构类型 成员变量处理 成员变量注册 模板匹配防止编译报错 成员变量匹配Key重命名 Object2Json实现 亮点 源码 参考文档 总结 背景 C/C++客户端需要接收和发送JSON格式的数据到后端以实现通讯和数据交互.C++没有现成的处理JSON格式数据的接口,直接引用第三方库还是避免不了拆解拼接.考虑到此项目将会有大量JSON数据需要处理,避免不了重复性的拆分拼接.所以打算封装一套C++结构体对象转JSON数据.JSON

  • 如何控制Go编码JSON数据时的行为(问题及解决方案)

    今天来聊一下我在Go中对数据进行 JSON 编码时遇到次数最多的三个问题以及解决方法,大家来看看是不是也为这些问题挠掉了不少头发. 自定义JSON键名 这个问题加到文章里我是有所犹豫的,因为基本上大家都会,不过属于同类问题我还是放进来了,对新接触 Go 的同学更友好些. 我们先从最常见的一个问题说,首先在Go 程序中要将数据编码成JSON 格式时通常我们会先定义结构体类型,将数据存放到结构体变量中. type Address struct { Type string City string Co

  • 解决Ajax加载JSon数据中文乱码问题

    一.问题描述 使用zTree的异步刷新父级菜单时,服务器返回中文乱码,但项目中使用了SpringMvc,已经对中文乱码处理,为什么还会出现呢? 此处为的异步请求的配置: Java代码 async: { enable: true, url: basePath + '/sysMenu/listSysMenu', autoParam: ["id=parentId"] } SpringMvc中文字符处理: Java代码 <mvc:annotation-driven> <mvc

  • ASP 处理JSON数据的实现代码

    ASP也能处理JSON数据?呵呵,刚才在Pjblog论坛上看到一个兄弟写的文章,没有测试,不过理论上一定是可以的~ 太晚了,不测试了. 以前处理JSON太麻烦了,输出还好说,循环一下就可以了,解析真的很头疼.所以遇到 这种问题API问题,一般都是XML处理,不太喜欢,很麻烦. <% Dim sc4Json Sub InitScriptControl Set sc4Json = Server.CreateObject("MSScriptControl.ScriptControl")

  • JQuery用$.ajax或$.getJSON跨域获取JSON数据的实现代码

    通过JQuery可以跨域获取JSON数据,但必须弄清楚的是,JQuery不可以跨域获取任意JSON格式的数据,必须要通过服务端输出特定的针对JQuery跨域读取的JSON数据.你可能目前对此仍然毫无了解,没关系,本文将以最简单易懂的方式介绍这个技术,相信人人都容易读懂,并能够实际应用. JQuery获取同域的JSON数据 首先引用jQuery库文件: <script src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js&quo

  • 如何实现json数据可视化详解

    前言 本文介绍的是如何实现json数据可视化,要用到的核心是JSON.stringify这个函数,没想到吧,平时我们只把它用来序列号json数据. JSON.stringify 函数 将 JavaScript 值转换为 JavaScript 对象表示法 (Json) 字符串. 语法 JSON.stringify(value [, replacer] [, space]) 参数 value 必需.  要转换的 JavaScript 值(通常为对象或数组). replacer 可选.  用于转换结果

  • 详解JSON1:使用TSQL查询数据和更新JSON数据

    JSON是一个非常流行的,用于数据交换的数据格式,主要用于Web和移动应用程序中.JSON 使用键/值对(Key:Value pair)存储数据,并且表示嵌套键值对和数组两种复杂数据类型,仅仅使用逗号(引用Key)和中括号(引用数组元素),就能路由到指定的属性或成员,使用简单,功能强大.在SQL Server 2016版本中支持JSON格式,使用Unicode字符类型表示JSON数据,并能对JSON数据进行验证,查询和修改.推荐一款JSON验证和格式化的工具:json formatter. 一,

  • ext前台接收action传过来的json数据示例

    ext前台接收action传过来的json数据 复制代码 代码如下: Ext.Ajax.request({ method:'POST',//请求方式 params : {dagl_code:dagl_code}, url:lcwPath+"/daxt/lcgl.shtml?method=getJgBycode",//请求的url地址 success: function(response, opts) { if(response.responseText!='{}'){ alert(re

  • Ajax异步请求JSon数据(图文详解)

    上一篇讲了Ajax请求数据text类型,text和html都是处理比较简答的数据,而在编程过程中使用Ajax调用数据的时候,难免要进行逻辑的处理,接受的数据也变的复杂比如数组类型的数据,这时候就需要使用JSON数据类型进行处理,今天就说说,JSON数据请求过程中的一些细节: 我们友情提醒本文所需工具和原料如下: wamp或lamp环境.jquery.js.编辑器 具体方法/步骤请看下面: 1.创建基本的文件结构json_ajax.html和json_ajax.php,下载jquery.js,如图

  • jquery的ajax异步请求接收返回json数据实例

    jquery的ajax异步请求接收返回json数据方法设置简单,一个是服务器处理程序是返回json数据,另一种就是ajax发送设置的datatype设置为jsonp格式数据或json格式都可以. 代码示例如下: 复制代码 代码如下: $('#send').click(function () {     $.ajax({         type : "GET",         url : "a.php",         dataType : "json

随机推荐