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}
};

参考文献

nlohmann/json 的主要用法 - 麦仲肥 - 博客园

c – 如何从nlohmann json获取数组 - 程序园

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐