一个好用的C++的json库

此文首发于我的个人博客:一个好用的C++的json库 — zhang0peter的个人博客


今天在找可以在C++中用的JSON库。
一个比较好用的传统的JSON库是JsonCpp, GitHub地址:jsoncpp: A C++ library for interacting with JSON.。但是安装起来比较麻烦:

sudo apt-get install libjsoncpp-dev 
sudo ln -s /usr/include/jsoncpp/json/ /usr/include/json

我选择了另外一个库,叫JSON for Modern C++,GitHub地址:nlohmann/json: JSON for Modern C++

这个库最大的优点是只要包含一个库文件就可以了,非常方便

在Releases 中下载单文件的json.hpp:Releases · nlohmann/json

运行示例如下:

#include <iostream>
#include <fstream>
#include <iomanip>
#include "json.hpp"

using namespace std;
using json = nlohmann::json;

int main(int argc, char **argv) {
    cout << "test start " << endl;


    // create an empty structure (null)
    json j;

    // add a number that is stored as double (note the implicit conversion of j to an object)
    j["pi"] = 3.141;

    // add a Boolean that is stored as bool
    j["happy"] = true;

    // add a string that is stored as std::string
    j["name"] = "Niels";

    // add another null object by passing nullptr
    j["nothing"] = nullptr;

    // add an object inside the object
    j["answer"]["everything"] = 42;

    // add an array that is stored as std::vector (using an initializer list)
    j["list"] = {1, 0, 2};

    // add another object (using an initializer list of pairs)
    j["object"] = {{"currency", "USD"},
                   {"value",    42.99}};

    // instead, you could also write (which looks very similar to the JSON above)
    json j2 = {
            {"pi",      3.141},
            {"happy",   true},
            {"name",    "Niels"},
            {"nothing", nullptr},
            {"answer",  {
                                {"everything", 42}
                        }},
            {"list",    {       1, 0, 2}},
            {"object",  {
                                {"currency",   "USD"},
                                   {"value", 42.99}
                        }}
    };


    string jsonFile = "new_tree.json";
    std::ofstream outFile(jsonFile);
    outFile << std::setw(4) << j << std::endl;

    std::cout << j.dump(4) << std::endl;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值