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

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

  • json11的github地址

https://github.com/dropbox/json11

  • 代码
cpp 复制代码
#include <iostream>
#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的接口。

  • JSON数据
json 复制代码
{"Address": [{"IP": "127.0.0.1", "Port": "10086"}, {"IP": "127.0.0.1", "Port": "10010"}], "ChanCode": "1", "ChanDesc": null, "ChanType": "5"}
相关推荐
不想写代码的星星1 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
端平入洛9 天前
auto有时不auto
c++
郑州光合科技余经理10 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12310 天前
matlab画图工具
开发语言·matlab
dustcell.10 天前
haproxy七层代理
java·开发语言·前端