问题
I have a JSON with nested objects (here is a made up example as the real json is bigger and complex). I need to Iterate through siblings
object. I know how to do it with array but could not find any example to deal with such nested object (of any nesting depth).
Any idea is appreciated.
{
.......
"siblings":{
"Michael":{
"age":20,
"lives":"Dodoma"
},
"Polyasi":{
"age":25,
"lives":"Geita"
},
"Kiah":{
"age":3,
"lives":"Dar es Salaam"
}
}
...........
}
回答1:
So I found that ValueMap::Iterator does not care whether it is an Object or atomic values it treats them the same. So here is an example that I coined to actually test this. Thanks to @atomic_alarm for pushing me into testing something I had given up as potential solution.
the packagist.json is actually renamed JSON file found here. Here is the code. Make sure that you link against foundation and json libraries.
#include <Poco/JSON/Parser.h>
#include <Poco/Dynamic/Var.h>
#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>
void print_version_names(Poco::JSON::Object::Ptr root);
int main(int argc, char** argv)
{
//read file
std::ifstream t("packagist.json");
std::string json_str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
Poco::JSON::Parser parser;
Poco::Dynamic::Var result = parser.parse(json_str);
Poco::JSON::Object::Ptr json = result.extract<Poco::JSON::Object::Ptr>();
print_version_names(json);
return 0;
}
void print_version_names(Poco::JSON::Object::Ptr root)
{
std::string root_key = "package";
std::string key = "versions";
//no checks whether such key acually exists
Poco::JSON::Object::Ptr package_json = root->getObject(root_key);
//get the nested objects
Poco::JSON::Object::Ptr nested_versions = package_json->getObject(key);
//iterate the map
Poco::JSON::Object::Iterator it;
for(it = nested_versions->begin(); it != nested_versions->end(); it++)
{
//no check of whether it is an object
std::cout<<it->first<<"\n";
}
}
Results:
2.0.0
2.0.0-alpha
2.0.0-beta
2.0.0-rc
2.0.1
2.0.10
2.0.11
2.0.11.1
2.0.11.2
2.0.12
2.0.2
2.0.3
2.0.4
2.0.5
2.0.6
2.0.7
2.0.8
2.0.9
来源:https://stackoverflow.com/questions/45044184/poco-iterating-nested-json-objects