C++第三方库【JSON】nlohman/json-使用

时间:2025-04-17 08:08:52

直接包含

dir/
└── nlohmann
    ├── json_fwd.hpp
    └── json.hpp
└── a.cpp

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

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

#include <iostream>
#include "nlohmann/json.hpp"

using json = nlohmann::json;

int main()
{
    // 使用不同类型的默认值创建JSON值
    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);

    // 序列化JSON值
    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
{}
[]
""