c++11 - How to create and parse hierarchical/nested JSON with Poco C++? -
edited simplify , show exact code.
i have following data need serialize json parse json.
string name; std::map<string, string> metadata;
i need json nested/hierarchical this:
{ "name":"john smith" "metadata": { "age":45, "middle_name":"william", }, }
here exact code:
void deserializefromjson(string &jsonstring) { // parse json poco::json::parser jsonparser; poco::dynamic::var parsedjson = jsonparser.parse(jsonstring); poco::dynamic::var parsedresult = jsonparser.result(); // extract json object poco::dynamicstruct jsonstruct = *parsedresult.extract<poco::json::object::ptr>(); // name name = jsonstruct["name"].tostring(); // meta data -- of these should use??? poco::dynamic::var metavar = jsonstruct["metadata"]; poco::json::object metaobj = jsonstruct["metadata"]; // @ point, have in 'metavar' , 'metaobj'? // if try loop say, compiler error c2664 in "var.h" (poco::json::object::constiterator itr = jsonobject.begin(), end = jsonobject.end(); itr != end; ++itr) { string metaname = itr->first; string metavalue = itr->second.tostring(); } }
update: while putting example, found a subtle bug; fixed in repo upcoming 1.6.1 , 1.7.0 release. sample below works fine earlier releases, don't use preserve order json::stringifier::stringify() (using object::stringify() fine).
here go; if don't care preserving json entries insertion order, don't pass object constructor - perform better:
#include "poco/json/parser.h" #include "poco/json/parsehandler.h" #include "poco/json/stringifier.h" using poco::json::parsehandler; using poco::json::stringifier; using poco::json::object; using poco::json::parser; using poco::dynamic::var; using poco::dynamicstruct; void objprint(object& obj, const std::string& name = "") { (object::constiterator = obj.begin(), end = obj.end(); != end; ++it) { if (!name.empty()) std::cout << name << ':'; std::cout << it->first << ':'; if (it->second.type() == typeid(object::ptr)) { object::ptr p = it->second.extract<object::ptr>(); objprint(*p, it->first); } else std::cout << it->second.tostring() << std::endl; } } int main(int, char**) { typedef std::map<std::string, int> personmap; std::string timestamp = "2015-05-14t17:47:21.999z"; poco::int32 identifier = 3; std::string name = "john smith"; personmap metadata; metadata.insert(personmap::value_type("william", 45)); object obj(true); obj.set("ts", timestamp); obj.set("name", name); obj.set("identifier", identifier); object::ptr pmd = new poco::json::object(true); (personmap::iterator = metadata.begin(), end = metadata.end(); != end; ++it) { pmd->set("middle_name", it->first); pmd->set("age", it->second); } obj.set("metadata", pmd); std::ostringstream os; obj.stringify(os, 2); std::cout << os.str() << std::endl; parser parser; var result = parser.parse(os.str()); object::ptr pobj = result.extract<object::ptr>(); objprint(*pobj); return 0; }
Comments
Post a Comment