JSON_Spirit: как получить значение

Я работаю с cpp, чтобы построить проект.

Моему проекту нужен файл для некоторой настройки, и я решил использовать файл в формате JSON. Вот пример:

{
    "agentname":"agent1",
    "server":[
        {"ip":"192.168.0.1"},
        {"port":"9999"}
    ]    
}

Теперь мне нужно прочитать этот файл, поэтому я использую JSON_Spirit. Вот мой код:

ifstream conf("config", ios::in);
json_spirit::mValue mvalue;
json_spirit::read(conf, mvalue);
json_spirit::mObject obj = mvalue.get_obj();
string agentname = obj.find("agentname")->second.get_str();

После кода я могу получить agentname,
Но я не знаю, как получить ip а также port,
Я пытался так:

string ip = obj.find("server")->second.find("ip")->second.get_str();

Я думаю, что это должно быть что-то вроде этого, но приведенный выше код не работает.

1 ответ

Решение

Я считаю, что с json_spirit помогает иметь несколько функций доступа к утилитам. Кроме того, внимательно изучите фактическое содержание документа:

Это будет работать:

#include <json_spirit.h>
#include <iostream>
#include <sstream>

using namespace std;

const string test_str =
R"json({
    "agentname":"agent1",
    "server":[
          {"ip":"192.168.0.1"},
          {"port":"9999"}
    ]
}
)json";

json_spirit::mValue read_document(std::istream& is) {
    json_spirit::mValue result;
    auto ok = json_spirit::read(is, result);
    if (!ok) {
        throw std::runtime_error { "invalid json" };
    }
    return result;
}

const json_spirit::mValue& get_object_item(const json_spirit::mValue& element, const std::string& name)
{
    return element.get_obj().at(name);
}

const json_spirit::mValue& get_array_item(const json_spirit::mValue& element, size_t index)
{
    return element.get_array().at(index);
}

int main()
{
    istringstream conf(test_str);

    auto doc = read_document(conf);

    const auto& agentname = get_object_item(doc, "agentname");
    const auto& server = get_object_item(doc, "server");
    const auto& ip_holder = get_array_item(server, 0);
    const auto& ip = get_object_item(ip_holder, "ip");
    const auto& port = get_object_item(get_array_item(server, 1), "port");

    cout << agentname.get_str() << endl
    << ip.get_str() << endl
    << port.get_str() << endl;

    return 0;
}

ожидаемый результат:

agent1
192.168.0.1
9999
Другие вопросы по тегам