C++使用json11开源库快速生成JSON格式的数据

csdn推荐

在程序开发中,JSON格式的接口数据应用很广泛,C++生态中有许多高效的JSON库,如nlohmann/json、RapidJSON、jsoncpp等,这些库提供了便捷的API来实现JSON数据的解析、生成、序列化和反序列化,简化了C++程序对JSON数据的操作,本文记录一个轻量级的开源库json11来生成JSON格式的数据。

#include 
#include "json11.hpp"
using namespace std;
int main()
{
    // JSON对象
    json11::Json::object root;
    root["ChanCode"] = "1";
    root["ChanDesc"] = nullptr;
    root["ChanType"] = "5";
    // JSON数组
    json11::Json::array subArray;
    json11::Json::object subObj1;
    subObj1["IP"] = "127.0.0.1";
    subObj1["Port"] = "10086";
    json11::Json::object subObj2;
    subObj2["IP"] = "127.0.0.1";
    subObj2["Port"] = "10010";
    // JSON数组添加元素
    subArray.push_back(subObj1);
    subArray.push_back(subObj2);
    root["Address"] = subArray;
    json11::Json json = root;
    std::string strJson = json.dump();
    cout << strJson << endl;
    cout << strJson.length() << endl;
    return 0;
}

json11是C++11的一个小型JSON库,提供JSON解析和序列化。在使用过程中只需要引用json11.hpp和json11.cpp两个文件即可使用json11的接口。

{"Address": [{"IP": "127.0.0.1", "Port": "10086"}, {"IP": "127.0.0.1", "Port": "10010"}], "ChanCode": "1", "ChanDesc": null, "ChanType": "5"}

文章来源:https://blog.csdn.net/Love_XiaoQinEr/article/details/138505201



微信扫描下方的二维码阅读本文

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容