Как разобрать json с помощью nlohmann lib? - PullRequest
1 голос
/ 09 марта 2020

Я использую эту библиотеку для 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 Мне нужно использовать другой способ, но какой?

1 Ответ

1 голос
/ 09 марта 2020

Загрузка 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';
    }
}
...