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");
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。