json.hpp

Posted by shensunbo on January 20, 2025

常用操作

读取数组

1
2
3
4
"ceer_color": [1.0, 1.0, 0.0, 0.3],

std::vector<int> color = block.at("color").get<std::vector<int>>();
tmp_block.color = glm::vec3(color.at(0), color.at(1), color.at(2)) / 255.0f;

使用 find()方法检查存在性

1
2
3
4
5
6
7
auto it = j.find("name");
if (it != j.end()) {
    std::string name = it.value();
    std::cout << "找到name: " << name << std::endl;
} else {
    std::cout << "name字段不存在" << std::endl;
}

使用 contains()检查存在性

1
2
3
4
5
6
7
8
if (j.contains("name")) {
    std::string name = j["name"];
}

// 检查嵌套字段
if (j.contains("address") && j["address"].contains("city")) {
    std::string city = j["address"]["city"];
}

get 和 get_to 方法

  • get()用于创建新对象并返回该对象的副本
  • get_to()用于将值赋给已存在的对象(原地修改)

    使用 get_to() 可以避免不必要的对象复制,提高性能,尤其是对于大型数据结构。

支持的数据类型

  • 基本类型:int, float, double, bool, string
  • 容器类型:vector, list, map, set
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// std::vector
std::vector<int> vec = {1, 2, 3};
json j_vec = vec;
auto vec_back = j_vec.get<std::vector<int>>();

// std::deque
std::deque<std::string> deq = {"a", "b", "c"};
json j_deq = deq;

// std::list
std::list<double> lst = {1.1, 2.2, 3.3};
json j_lst = lst;

// std::forward_list
std::forward_list<bool> flst = {true, false, true};
json j_flst = flst;

// std::array (固定大小)
std::array<int, 3> arr = {1, 2, 3};
json j_arr = arr;
auto arr_back = j_arr.get<std::array<int, 3>>();

// std::map / std::unordered_map
std::map<std::string, int> map = {{"a", 1}, {"b", 2}};
json j_map = map;
auto map_back = j_map.get<std::map<std::string, int>>();

std::unordered_map<std::string, double> umap = {{"x", 1.0}, {"y", 2.0}};
json j_umap = umap;

// std::set / std::unordered_set
std::set<int> set = {1, 2, 3};
json j_set = set;

std::unordered_set<std::string> uset = {"apple", "banana"};
json j_uset = uset;

// std::multiset / std::multimap 也支持
std::multimap<std::string, int> multimap = {{"a", 1}, {"a", 2}};
json j_multimap = multimap;

对类型、元组和变体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <tuple>
#include <variant>

// std::pair
std::pair<std::string, int> p = {"key", 42};
json j_pair = p;
auto p_back = j_pair.get<std::pair<std::string, int>>();

// std::tuple
std::tuple<int, std::string, bool> t = {1, "hello", true};
json j_tuple = t;
auto t_back = j_tuple.get<std::tuple<int, std::string, bool>>();

// std::variant (C++17)
std::variant<int, std::string, bool> v = "test";
json j_variant = v;
auto v_back = j_variant.get<std::variant<int, std::string, bool>>();

// std::optional (C++17)
std::optional<int> opt1 = 42;
std::optional<int> opt2 = std::nullopt;
json j_opt1 = opt1;  // 值为42
json j_opt2 = opt2;  // 值为null

自定义类型

TODO: