nlohmann-json使用

nlohmann/json

nlohmann/json是一个使用现代c++编写的一个json库,该库是head-only的。

json介绍

关于json的介绍可以参考:CJSON简单介绍

使用

直接包含

single_include/
└── nlohmann
    ├── json_fwd.hpp
    └── json.hpp

一般只要包含json.hpp,如果需要forward-declarations那么可以包含json_fwd.hpp。

注意,因为库使用了c++11特性,所以在编译的时候需要用C++11以上的标准编译。

#include 
#include "include/single_include/nlohmann/json.hpp"

using json = nlohmann::json;

int main()
{
    // create the different JSON values with default values
    json j_null(json::value_t::null);
    json j_boolean(json::value_t::boolean);
    json j_number_integer(json::value_t::number_integer);
    json j_number_float(json::value_t::number_float);
    json j_object(json::value_t::object);
    json j_array(json::value_t::array);
    json j_string(json::value_t::string);

    // serialize the JSON values
    std::cout << j_null << '\n';
    std::cout << j_boolean << '\n';
    std::cout << j_number_integer << '\n';
    std::cout << j_number_float << '\n';
    std::cout << j_object << '\n';
    std::cout << j_array << '\n';
    std::cout << j_string << '\n';
}

运行结果:

$./a.out 
null
false
0
0.0
{}
[]
""

例子

从文件中导入json对象

#include 
#include 
using json = nlohmann::json;

// ...

std::ifstream f("example.json");
json data = json::parse(f);

使用json字面量创建json对象

// Using (raw) string literals and json::parse
json ex1 = json::parse(R"(
  {
    "pi": 3.141,
    "happy": true
  }
)");

// Using user-defined (raw) string literals
using namespace nlohmann::literals;
json ex2 = R"(
  {
    "pi": 3.141,
    "happy": true
  }
)"_json;

// Using initializer lists
json ex3 = {
  {"happy", true},
  {"pi", 3.141},
};

直接创建并操作json对象

// 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}
  }}
};

限制

字符集

只支持UTF-8作为输入

注释

不支持json注释

key的顺序

默认不保存json中key的顺序,即打印的key的顺序是随机的。如果要支持,使用nlohmann::ordered_json试试。

参考

https://json.nlohmann.me/
https://github.com/miloyip/nativejson-benchmark

你可能感兴趣的:(lib,Reference,json)