Search code examples
c++jsonpoco-libraries

Correct usage of Poco C++ JSON for parsing data


Can anyone instruct me on how the Poco C++ JSON works?

Previously I've used JsonReader and JsonToken. The Poco C++ library doesn't seem to have corresponding objects.

How do I for example use the json parser to create a object name consisting the JSON value at the tag name?


Solution

  • EDIT: as of 1.5.2, things were simplified by making DefaultHandler, well ... default (and renaming it to its proper name - ParseHandler. So, if all you need is parsing, no need to explicitly provide the handler anymore:

    // objects
    std::string json = "{ \"test\" : { \"property\" : \"value\" } }";
    Parser parser;
    Var result = parser.parse(json);
    Object::Ptr object = result.extract<Object::Ptr>();
    Var test = object->get("test");
    object = test.extract<Object::Ptr>();
    test = object->get("property");
    std::string value = test.convert<std::string>();
    
    // array of objects
    std::string json = "[ {\"test\" : 0}, { \"test1\" : [1, 2, 3], \"test2\" : 4 } ]";
    Parser parser;
    Var result = parser.parse(json);
    Array::Ptr arr = result.extract<Array::Ptr>();
    Object::Ptr object = arr->getObject(0);//
    assert (object->getValue<int>("test") == 0);
    object = arr->getObject(1);
    arr = object->getArray("test1");
    result = arr->get(0);
    assert (result == 1);
    

    See this answer for more details.