nlohmann_json

nlohmann_json 是一个简单好用的 json 序列化和反序列化库,提供了以下功能:

  • 对 C++ 及标准库中的类型进行序列化和反序列化

  • 非侵入式的序列化和反序列化功能

  • 将 JSON 导出到二进制数据

  • 无异常模式

  • 自定义解析工具

自定义解析器

在某些场景下我们可能希望即使 json 是错误的,也提供尽量解析的能力,此时可以使用下面的方式:

class sax_no_exception : public nlohmann::detail::json_sax_dom_parser<nlohmann::json> {
public:
   sax_no_exception(nlohmann::json& j) : nlohmann::detail::json_sax_dom_parser<nlohmann::json>(j, false) { }

   bool parse_error(std::size_t position, const std::string& last_token, const nlohmann::json::exception& ex) {
       return false;
   }
};

std::string myinput = "[1,2,3,]";
json result;
sax_no_exception sec(result);
// 当 json 存在错误时 result 为 false
bool parse_result = json::sax_parse(,&sax);
// 使用 result 获取解析结果
// ...

序列化自定义类型

nlohmann_json 可以序列化标志库中的对象和容器,例如 std::string, std::vector, std::tuple 等等,但是自定义类型需要自己实现相关的 from_json 和 to_json 函数:

// a simple struct to model a person
struct person {
    std::string name;
    std::string address;
    int age;
};

void to_json(json& j, const person& p) {
   j = json{
       {"name", p.name},
       {"address", p.address},
       {"age", p.age}
   };
}

void from_json(const json& j, person& p) {
    j.at("name").get_to(p.name);
    j.at("address").get_to(p.address);
    j.at("age").get_to(p.age);
}

序列化枚举

例如:

// example enum type declaration
enum TaskState {
    TS_STOPPED,
    TS_RUNNING,
    TS_COMPLETED,
    TS_INVALID=-1,
};

// map TaskState values to JSON as strings
NLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {
    {TS_INVALID, nullptr},
    {TS_STOPPED, "stopped"},
    {TS_RUNNING, "running"},
    {TS_COMPLETED, "completed"},
})
Last moify: 2022-12-04 15:11:33
Build time:2025-07-18 09:41:42
Powered By asphinx