服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++对Json数据的友好处理实现过程

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

2022-09-21 14:39雪影蓝枫 C/C++

在Ajax的应用中,前台基本上会用到JSON作为数据交换格式,所以下面这篇文章主要给大家介绍了关于C++对Json数据的友好处理,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

背景

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转换

效果:

先上单元测试代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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等基本数据类型,该实现均较为简单:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*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节点一一对应,并能够匹配进行数据填充。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/*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的特性——可变参数模板,从里到外遍历处理每个成员变量
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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名称列表。
?
1
2
3
4
5
6
#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并带上成员变量的注册声明:

?
1
2
3
4
5
6
7
8
9
struct DemoObjct
 {
     bool boolValue;
     int intValue;
     std::string strValue;
    
    JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)
        
 };

等同于:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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来给未声明注册宏的结构体提供缺省函数。

?
1
2
3
4
5
6
7
8
9
10
11
12
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,例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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串转结构体切换自如

源码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#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数据的处理内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/liaoguifa/p/15883417.html

延伸 · 阅读

精彩推荐
  • C/C++C语言中%c与%s的区别与划分详解

    C语言中%c与%s的区别与划分详解

    这篇文章主要介绍了C语言中%c与%s的区别与划分详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    zhgl76885302021-10-08
  • C/C++C语言中如何简单的读取文件中的数据

    C语言中如何简单的读取文件中的数据

    本文主要讲解C语言中如何简单的读取文件中的数据,有需要的朋友可以参考下...

    狂奔的Snail3692020-10-18
  • C/C++详解C语言中fseek函数和ftell函数的使用方法

    详解C语言中fseek函数和ftell函数的使用方法

    这篇文章主要介绍了C语言中fseek函数和ftell函数的使用方法,两个函数分别用于设置和返回文件指针stream的位置,需要的朋友可以参考下...

    YoferZhang9832021-03-27
  • C/C++C语言模拟实现扫雷游戏

    C语言模拟实现扫雷游戏

    这篇文章主要为大家详细介绍了C语言模拟实现扫雷游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Skyline-sjc12292021-10-20
  • C/C++short与int转换的小例子

    short与int转换的小例子

    short与int转换的小例子,需要的朋友可以参考一下...

    C语言中文网8762020-11-20
  • C/C++C语言实现简单电子通讯录(2)

    C语言实现简单电子通讯录(2)

    这篇文章主要为大家详细介绍了C语言实现简单电子通讯录的第二部分,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    believe_s9272021-09-14
  • C/C++C语言:十进制,BCD码互换详解

    C语言:十进制,BCD码互换详解

    这篇文章主要介绍了C语言十进制,BCD码互换实例,小编觉得这篇文章写的还不错,实例简单明了,需要的朋友可以参考下...

    不脱发的程序猿12042021-12-27
  • C/C++codeblocks 对‘cv::waitKey(int)’未定义的引用方式

    codeblocks 对‘cv::waitKey(int)’未定义的引用方式

    今天小编就为大家分享一篇codeblocks 对‘cv::waitKey(int)’未定义的引用方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    ShellCollector3902021-08-08