1.JSON
1.JSON简介
JSON(JavaScript Object Notation)是一种轻量级的数据序列化协议,基于文本,完全独立于语言。
JSON由键值对组成,支持以下几种数据类型:
-
字符串:用双引号括起来的文本。
-
数字:整数或浮点数。
-
布尔值:
true
或false
。 -
数组:用方括号
[]
括起来的有序数据集合,数组中的元素可以是任何类型。 -
对象:用花括号
{}
括起来的无序键值对集合。 -
null:表示空值。
2.JSON for Modern C++(
JSON for Modern C++(通常称为 nlohmann/json)是一个非常流行的现代 C++ JSON 库,它以简洁、易用和符合现代 C++ 编程风格而闻名。以下是它的简单介绍:
- 单头文件库:整个库由一个头文件
json.hpp
组成,无需复杂的安装过程。 -
类型安全:所有操作都经过严格的类型检查,避免了常见的错误。
-
与 STL 容器无缝集成:可以直接与
std::vector
、std::map
等标准库容器进行转换。 -
丰富的功能:支持 JSON 指针、JSON 补丁、自动类型推导等高级特性。
-
易于使用:API 设计简洁直观,适合快速开发。
3.json.hpp使用
1. 序列化(C++ 对象到 JSON 字符串)
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// 创建一个 C++ 对象
json j = {
{"name", "Alice"},
{"age", 25},
{"city", "New York"}
};
// 序列化为 JSON 字符串
std::string json_str = j.dump();
// 输出 JSON 字符串
std::cout << "Serialized JSON: " << json_str << std::endl;
return 0;
}
-
nlohmann::json
支持从标准容器(如std::vector
)自动序列化:nlohmann::json
库会自动遍历std::vector
中的每个元素,并调用每个元素类型的to_json
函数(如果定义了)来序列化每个元素。inline void to_json(nlohmann::json &js, const ChunkMeta &cm) { js = nlohmann::json{{"chunk_id", cm.chunk_id}, {"file_id", cm.file_id}, {"index", cm.index}, {"size", cm.size}, {"checksum", cm.checksum}}; }
2. 反序列化(JSON 字符串到 C++ 对象)
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// JSON 字符串
std::string json_str = R"({"name": "Alice", "age": 25, "city": "New York"})";
// 反序列化为 C++ 对象
json j = json::parse(json_str);
// 访问解析后的数据
std::cout << "Name: " << j["name"] << std::endl;
std::cout << "Age: " << j["age"] << std::endl;
std::cout << "City: " << j["city"] << std::endl;
return 0;
}
3.get
get()
方法用于将 JSON 值转换为指定的类型。其基本语法如下:
Type value = json_object["key"].get<Type>();
Type value = json_object.get<Type>("key");