gpt4 book ai didi

c++ - JSON_Spirit : how to get value

转载 作者:行者123 更新时间:2023-11-30 03:53:01 26 4
gpt4 key购买 nike

我正在使用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();

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

最佳答案

我发现使用 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

关于c++ - JSON_Spirit : how to get value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30350851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com