c++ - 如何使用nlohmann lib解析json?

标签 c++ json nlohmann-json

我使用这个库进行json解析https://github.com/nlohmann/json

我需要解析这个json文件

{
  "emulators": [
    {
      "general_info": {
        "dev_id": "0123456789",
        "model": "my_model",
        "model_full": "my_full_model",
        "serial_num": "my_serial_num"
      }
    }
  ]
}

我正在尝试这样做
void EmulatorCameraConfigParser::GetEmulatorContextObjFrom(std::string path_to_configuration_json, std::vector<emulator_context::EmulatorContextObj> * out_arr)
{
    json jf = Utils::get_json_data(path_to_configuration_json);

    if (jf == nullptr)
    {
        //TODO print - "Configuration json file for TV_CamFromFiles is null";
    }
    else
    {
        try
        {
            for (auto& elem : jf[EMULATORS])
            {
                emulator_context::EmulatorContextObj tmp;

                tmp.m_general_info = &get_general_info(elem[GENERAL_INFO]);
                out_arr->push_back(tmp);
            }
        }
        catch (std::exception& ex)
        {
            //TODO print error
            std::string errMsg = "Exeption during parsing configuration json file for TV_CamFromFiles :: ";
            errMsg += ex.what();
        }
    }
}
emulator_context::GeneralInfo EmulatorCameraConfigParser::get_general_info(const json& json)
{
    emulator_context::GeneralInfo generalInfo;

    try
    {
        if (json != nullptr)
        {
            generalInfo.m_dev_id = json.at(DEV_ID).get<std::string>();
            generalInfo.m_serial_num = json.at(SERIAL_NUM).get<int>();
        }
    }
    catch (std::exception& ex)
    {
        //TODO print this error
        std::string errMsg = "Exeption during parsing configuration json file for TV_CamFromFiles :: ";
        errMsg += ex.what();
    }

    return generalInfo;
}

但是结果一无所获,所以我几乎可以确定问题出在这里tmp.m_general_info = &get_general_info(elem[GENERAL_INFO]);
我认为为了获取general_info块,我需要使用其他方式,但是哪一种呢?

最佳答案

从文件加载json比这更简单。

#include <nlohmann/json.hpp>

#include <iostream>
#include <sstream>
#include <string>

using json = nlohmann::json;

int main() {
    // open the json file - here replaced with a std::istringstream containing the json data

    std::istringstream file(R"json({
  "emulators": [
    {
      "general_info": {
        "dev_id": "0123456789",
        "model": "my_model",
        "model_full": "my_full_model",
        "serial_num": "my_serial_num"
      }
    }
  ]
})json");

    // declare your json object and stream from the file
    json j;
    file >> j;

    // the file is now fully parsed

    // access fields
    for(json& o : j["emulators"]) {
        json& gi = o["general_info"];
        std::cout << gi["dev_id"] << '\n';
        std::cout << gi["model"] << '\n';
        std::cout << gi["model_full"] << '\n';
        std::cout << gi["serial_num"] << '\n';
    }
}

输出量
"0123456789"
"my_model"
"my_full_model"
"my_serial_num"

您还可以添加自己的序列化器支持:
#include <nlohmann/json.hpp>

#include <iostream>
#include <sstream>
#include <string>

using json = nlohmann::json;

struct general_info {
    std::string dev_id;
    std::string model;
    std::string model_full;
    std::string serial_num;
};

// conversion functions for your general_info
void to_json(json& j, const general_info& gi) {
    j = json{{"dev_id", gi.dev_id},
             {"model", gi.model},
             {"model_full", gi.model_full},
             {"serial_num", gi.serial_num}};
}

void from_json(const json& j, general_info& gi) {
    j.at("dev_id").get_to(gi.dev_id);
    j.at("model").get_to(gi.model);
    j.at("model_full").get_to(gi.model_full);
    j.at("serial_num").get_to(gi.serial_num);
}

int main() {
    std::istringstream file(R"json({
  "emulators": [
    {
      "general_info": {
        "dev_id": "0123456789",
        "model": "my_model",
        "model_full": "my_full_model",
        "serial_num": "my_serial_num"
      }
    }
  ]
})json");

    // declare your json object and stream from the file
    json j;
    file >> j;

    // convert a json array of "general_info" to a std::vector<general_info>

    json& arr = j["emulators"];

    std::vector<general_info> gis;

    std::for_each(arr.begin(), arr.end(), [&gis](const json& o) {
        if(auto it = o.find("general_info"); it != o.end()) {
            gis.push_back(it->get<general_info>());
        }
    });

    for(general_info& gi : gis) {
        std::cout << gi.dev_id << '\n';
        std::cout << gi.model << '\n';
        std::cout << gi.model_full << '\n';
        std::cout << gi.serial_num << '\n';
    }
}

关于c++ - 如何使用nlohmann lib解析json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60603487/

相关文章:

javascript - AJAX jquery json发送数组到php

javascript - Google Chrome 中的意外 token ILLEGAL javascript 错误

c++ - 使用 nlohmann json 将整数列表解包为 std::vector<int>

c++ - Nlohmann json 获取类型推导

c++ - 由解决方法 : c++ : boost_log : how does compiler choose st or mt 修复

c++ - 多层次的友元

c++ - 使用 mysql 连接器构建程序时出错

c++ - 我怎样才能从小数中得到分子和分母?

javascript - 来自服务器端的 JSON 字符串无法使用 ajax jquery 正确发送

c++ - 使用 CMake 添加仅 header 依赖项