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

本文介绍了如何在C++中封装一套结构体对象与JSON数据之间的转换接口,以简化JSON处理并提高开发效率。文章详细讲解了设计目标、实现过程,包括基本数据类型转换、自定义数据结构类型的处理,并使用JsonCPP库作为底层支持。此外,还讨论了成员变量的处理、注册、模板匹配以及重命名Key的方法。
摘要由CSDN通过智能技术生成

Python微信订餐小程序课程视频

https://edu.csdn.net/course/detail/36074

Python实战量化交易理财系统

https://edu.csdn.net/course/detail/35475

背景

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

设计

目标:

  1. 通过简单接口就能将C++结构体对象实例转换为JSON字符串数据,或将一串JSON字符串数据加载赋值到一个C++结构体对象实例。理想接口:Json2Object(inJsonString, outStructObject),或者Object2Json(inStructObject, outJsonString)
  2. 支持内置基本类型如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)
  • <
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,可以使用第三方库来处理JSON数据的存储和解析。其中,比较流行的有: 1. RapidJSON:一个快速的、DOM风格的、C++11 JSON解析器和生成器。它具有高性能、低内存占用和易于使用的特点。 2. jsoncpp:一个轻量级的C++ JSON解析器和生成器。它支持标准的JSON格式,并提供了友好的API接口。 3. Boost.PropertyTree:一个基于Boost库的C++属性树库,可以用于处理各种格式的数据,包括JSON。 以下是使用RapidJSON库将JSON数据存储到文件中的示例代码: ```cpp #include <iostream> #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <fstream> using namespace rapidjson; int main() { // 创建一个JSON对象 Document doc; doc.SetObject(); // 添加几个键值对 Value name; name.SetString("Tom", doc.GetAllocator()); doc.AddMember("name", name, doc.GetAllocator()); Value age; age.SetInt(20); doc.AddMember("age", age, doc.GetAllocator()); Value hobbies; hobbies.SetArray(); Value hobby1; hobby1.SetString("reading", doc.GetAllocator()); hobbies.PushBack(hobby1, doc.GetAllocator()); Value hobby2; hobby2.SetString("sports", doc.GetAllocator()); hobbies.PushBack(hobby2, doc.GetAllocator()); doc.AddMember("hobbies", hobbies, doc.GetAllocator()); // 将JSON对象转换成字符串 StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); std::string jsonStr = buffer.GetString(); // 将JSON字符串存储到文件中 std::ofstream ofs("data.json"); if (ofs.is_open()) { ofs << jsonStr; ofs.close(); } return 0; } ``` 该示例代码创建了一个JSON对象,添加了几个键值对,并将其转换成字符串后存储到文件中。文件内容如下所示: ```json {"name":"Tom","age":20,"hobbies":["reading","sports"]} ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值