1

我正在与 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.
但我不知道如何获得ipport
我试过这样:

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

我认为它应该是这样的,但上面的代码不起作用。

4

1 回答 1

2

我发现使用 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
于 2015-05-20T13:54:14.850 回答