Linux/Windows-好用的C++的json库--JsonCpp与JSON for Modern C++

2019/06/17 C++

此文首发于我的个人博客: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.hppReleases · 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;
}

Table of Contents