I am working with cpp to build a project.
My project needs a file to do some configuration and I decided to use a file with JSON format. Here is an example:
{
"agentname":"agent1",
"server":[
{"ip":"192.168.0.1"},
{"port":"9999"}
]
}
Now I need to read this file so I use the JSON_Spirit. Here is my code:
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();
After the code, I can get agentname
.
But I don't know how to get ip
and port
.
I have tried like this:
string ip = obj.find("server")->second.find("ip")->second.get_str();
I think it should be something like this but the code above doesn't work.
I find that with json_spirit it helps to have a few utility accessor functions. Also, take care to examine the actual contents of the document:
This will work:
#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;
}
expected output:
agent1
192.168.0.1
9999