nlohmann/json使用笔记
nlohmann/json 是一个用于解析json的开源c++库,口碑一流,号称有业界最好的性能,并且使用非常方便直观,是很多c++程序员的首选。开源官网处有详细说明用法,但篇幅过长,不便于迅速阅读抓重点。而且,所举例的某些用法实践上其实比较少用到,而某些实践上常用到的一些用法,官网却缺例子。所以自己简要总结了一下它的主要用法,并加上自己写的示例,希望能给到新接触该库的朋友一些帮助。#includ
·
nlohmann/json是一个用于解析json的开源C++库,口碑一流,号称有业界最好的性能,并且使用非常方便直观,是很多c++程序员的首选。
#include "nlohmann/json.hpp"
1. 输入输出
1.1. 输入
1.1.1. 从流输入
nlohmann::json json_data;
std::ifstream(can_file_path.string()) >> json_data;
nlohmann::json front_left_wheel_speed_data = json_data["key"];
1.1.2. 从文件输入
std::ifstream ifs(json_path);
nlohmann::json json = json::parse(ifs);
1.1.3. 从nlohmann::json对象输入
#include "nlohmann/json.hpp"
nlohmann::json json;
int value = json["value"]
// 读取字典
std::string name, credits, ranking;
json.at("name").get_to(name);
json.at("credits").get_to(credits);
json.at("ranking").get_to(ranking);
// 读取数组
nlohmann::json data = commands["Data"];
std::cout << "Number of items in Data: " << data.size() << std::endl;
for (auto it = data.begin(); it != data.end(); ++it) {
std::cout << it.key() << ": " << it.value() << std::endl;
}
std::string GetString(const nlohmann::json &json, const std::string &key) {
const auto iter = json.find(key);
if (iter == json.end()) {
std::cerr << "The json has no such key: " << key << std::endl;
}
if (!iter->is_string()) {
std::cerr << "The value of json[" << key << "] is not a string" << std::endl;
}
return *iter;
}
1.2. 输出
std::ofstream("rankings.json") << j;
2. 解析与序列化
2.1. 从字符串解析
std::string s = R"({
"name": "Judd Trump",
"credits": 1754500,
"ranking": 1
})";
auto j = json::parse(s);
2.3. 序列化为字符串
std::string s = j.dump();
3. 声明与构造
3.1. 纯粹声明
json j1;
json j2 = json::object();
json j3 = json::array();
std::cout << j1.type_name() << std::endl; // output: null
std::cout << j2.type_name() << std::endl; // output: object
std::cout << j3.type_name() << std::endl; // output: array
3.2. 内容构造
json j = R"({
"name": "Judd Trump",
"credits": 1754500,
"ranking": 1
})"_json;
json j{
{ "name", "Judd Trump"},
{ "credits", 1754500 },
{ "ranking", 1}
};
参考文献
更多推荐
已为社区贡献9条内容
所有评论(0)