Nlohmann Json是一个为现代 C++ 设计的高效 JSON 库。其核心功能是在 C++ 的数据结构与标准 JSON 格式之间进行灵活、直观的相互转换。
基本使用方法
#include<iostream>
#include"json.hpp" // 引入
using json = nlohmann::json;
int main() {
json j1, j2;
//通过[]直接创建json对象
j1["name"] = "Bob";
j1["age"] = 18;
//通过字面量创建json对象
j2 = json::parse(R"(
{
"name": "Alice",
"age": 18
}
)");
//json对象转换为字符串输出
std::cout << j1.dump() << std::endl;
//{"age":18,"name":"Bob"}
//格式化输出
std::cout << j2.dump(4) << std::endl;
/*
{
"age": 18,
"name": "Alice"
}
*/
}代码框架分析
模板设计
template<template<typename U, typename V, typename... Args> class ObjectType =
std::map,
template<typename U, typename... Args> class ArrayType = std::vector,
class StringType = std::string, class BooleanType = bool,
class NumberIntegerType = std::int64_t,
class NumberUnsignedType = std::uint64_t,
class NumberFloatType = double,
template<typename U> class AllocatorType = std::allocator,
template<typename T, typename SFINAE = void> class JSONSerializer =
adl_serializer,
class BinaryType = std::vector<std::uint8_t>,
class CustomBaseClass = void>
class basic_json;该库采用高度可定制的模板设计,运用策略模式,核心类basic_json是一个模板类,允许用户自定义:容器类型(默认对象使用std::map,数组使用std::vector)、基本数据类型(字符串、数值、布尔等)、内存分配器、序列化器等。
值存储机制
union json_value
{
/// object (stored with pointer to save storage)
object_t* object;
/// array (stored with pointer to save storage)
array_t* array;
/// string (stored with pointer to save storage)
string_t* string;
/// binary (stored with pointer to save storage)
binary_t* binary;
/// boolean
boolean_t boolean;
/// number (integer)
number_integer_t number_integer;
/// number (unsigned integer)
number_unsigned_t number_unsigned;
/// number (floating-point)
number_float_t number_float;
// ...
}
struct data
{
/// the type of the current element
value_t m_type = value_t::null;
/// the value of the current element
json_value m_value = {};
// ...
}该库采用了标记联合的值存储机制,在data结构体中m_type是一个 enum ,负责标记 union 中存储数据的类型,m_value是真正存储数据的 union 类型变量,可以存储多种类型数据。
Hint: 使用 union 类型的好处是在一个变量中可以根据需要存储不同的数据类型,减少内存开支。
调用关系
