nlohmannjson使用笔记

发布时间 2023-10-27 10:35:23作者: 清哥他弟
  1. 使用引用获取字段值,以避免数据复制:
auto id = jfo["id"].get_ref<const std::string&>();
  1. 使用解引用访问字段值,提高效率并简化代码
if (auto it = jfo.find("transforms"); it != jfo.end()) {
  for (const auto& jto : *it) {
    auto id = jto["id"].get_ref<const std::string&>();
  }
}
  1. 使用指针->直接访问字段值,提高效率并简化代码,解引用和指针都返回值对象
if (auto it = j.find("separator"); it != j.end()) {
  auto id = it->get<std::string>();
}
  1. 使用结构化绑定同时引用访问键值对,提高效率并简化代码(c++17)
if (auto it = jfield.find("enums"); it != jfield.end()) {
  for (const auto& [key, value]  : it->items()) {
    // use key/value
  }
}
  1. 使用vector访问数组,简化代码
//"fields": ["a", "b", "c"]
auto fields = j["fields"].get<std::vector<std::string>>();

待续...