Skip to content

序列化

1. nlohmann_json

1.1. 安装

sh
git submodule add https://github.com/nlohmann/json third_party/nlohmann_json
cmake
set(JSON_ImplicitConversions OFF)
add_subdirectory(third_party/nlohmann_json)
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)

1.2. 使用

cpp
#include <nlohmann/json.hpp>

对象

cpp
nlohmann::json data;
data["key"] = "value"; // 直接调函数
data["a"]["b"] = "value"; // 可以创多级对象
data = nlohmann::json::object(); // 空对象
data.count("key");

列表

cpp
nlohmann::json data;
data.push_back("value"); // 直接调函数
data = nlohmann::json(std::vector<int>{1, 2, 3});
data = nlohmann::json::array(); // 空列表

查询

cpp
data.get<std::string>(); // 得到特定类型的数据
data.type(); // nlohmann::json::value_t::?
data.is_null();
data.is_boolean();
data.is_number();
data.is_object();
data.is_array();
data.is_string();

2. toml

https://github.com/marzer/tomlplusplus

可以单文件,直接使用 toml.hpp

cpp
#include <iostream>

#include "toml.hpp"

int main() {
    toml::table tbl;
    tbl = toml::parse_file("test.toml");
    std::cout << *tbl["a"].value<int>() << "\n";
}