Correct usage of Poco C++ JSON for parsing data
Asked Answered
T

3

24

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?

Trophoblast answered 13/3, 2013 at 13:46 Comment(0)
W
37

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.

Welldressed answered 14/3, 2013 at 21:25 Comment(5)
Thank you for the good example! What if the JSON string contains an array of multiple similar objects?Trophoblast
Will the memory usage improve is using a stream instead of a string?Trophoblast
see this answer for string/stream and the upcoming changesWelldressed
note: For POCO 1.6, DefaultHandler has been removed, see hereAmbrose
To be precise, DefaultHandler was removed in 1.5.2 relaseWelldressed
C
24
#include <iostream>
#include <string>
#include <Poco/JSON/JSON.h>
#include <Poco/JSON/Parser.h>
#include <Poco/Dynamic/Var.h>

using namespace std;
using namespace Poco::JSON;

string GetValue(Object::Ptr aoJsonObject, const char *aszKey) {
    Poco::Dynamic::Var loVariable;
    string lsReturn;
    string lsKey(aszKey);

    // Get the member Variable
    //
    loVariable = aoJsonObject->get(lsKey);

    // Get the Value from the Variable
    //
    lsReturn = loVariable.convert<std::string>();

    return lsReturn;
}

int main(int argc, char *argv[]) {
    string lsJson;
    Parser loParser;

    lsJson = "{\"TransactionCode\":\"000000\",\"FileRecordSequenceNumber\":\"111111\",\"TcrSequenceNumber\":\"222222\",\"TransactionRouteIndicator\":\"ABCDE\",\"MerchantEstablishmentNumber\":\"00000000000\",\"MerchantName\":\"BBBBBBBBB\",\"MerchantCity\":\"CCCCCCCC\"}";

    cout << lsJson << endl;

    // Parse the JSON and get the Results
    //
    Poco::Dynamic::Var loParsedJson = loParser.parse(lsJson);
    Poco::Dynamic::Var loParsedJsonResult = loParser.result();

    // Get the JSON Object
    //
    Object::Ptr loJsonObject = loParsedJsonResult.extract<Object::Ptr>();

    // Get the values for the member variables
    //
    //
    cout << "TransactionCode             " << GetValue(loJsonObject, "TransactionCode")               << endl;
    cout << "FileRecordSequenceNumber    " << GetValue(loJsonObject, "FileRecordSequenceNumber")      << endl;
    cout << "TcrSequenceNumber           " << GetValue(loJsonObject, "TcrSequenceNumber")             << endl;
    cout << "TransactionRouteIndicator   " << GetValue(loJsonObject, "TransactionRouteIndicator")     << endl;
    cout << "MerchantEstablishmentNumber " << GetValue(loJsonObject, "MerchantEstablishmentNumber")   << endl;
    cout << "MerchantName                " << GetValue(loJsonObject, "MerchantName")                  << endl;
    cout << "MerchantCity                " << GetValue(loJsonObject, "MerchantCity")                  << endl;

    return 0;

}

Results:
{"TransactionCode":"000000","FileRecordSequenceNumber":"111111","TcrSequenceNumber":"222222","TransactionRouteIndicator":"ABCDE","MerchantEstablishmentNumber":"00000000000","MerchantName":"BBBBBBBBB","MerchantCity":"CCCCCCCC"}
TransactionCode             000000
FileRecordSequenceNumber    111111
TcrSequenceNumber           222222
TransactionRouteIndicator   ABCDE
MerchantEstablishmentNumber 00000000000
MerchantName                BBBBBBBBB
MerchantCity                CCCCCCCC
Complaisant answered 12/9, 2013 at 23:50 Comment(2)
Works straight out of the box with Poco 1.6.0 , very niceAmbrose
+1 for showing #includes and usings. I don't understand why so many C++ examples don't show these, which are often the hardest part about figuring out how to work with the thing.Larena
U
0

From the fragment of Alex, which indexes into a Json array, I created a working example and added a loop over Json array.

Compiles with

g++ -std=c++20 -o json-array-poco json-array-poco.cpp  -lPocoRedis -lPocoUtil -lPocoNet -lPocoNetSSL -lPocoCrypto -lPocoXML -lPocoJSON -lPocoFoundation

Requires

sudo apt install libpoco-dev

Store into json-array-poco.cpp

    #include <iostream>
    #include <Poco/JSON/JSON.h>
    #include <Poco/JSON/Parser.h>
    #include <stack>

    using Poco::JSON::Parser;
    using std::cout;
    using std::stack;
    using std::string;


    void example_index_into_array (){
        Parser     parser;
        string     json_string      = R"(  {"data":[{"p":11,"t":1111},{"p":22,"t":2222}],"foo":"bar"}  )";
        auto       json_pocojson    = parser.parse(json_string).extract<Poco::JSON::Object::Ptr>();  // Specify type as Json
        auto       foo_string       = json_pocojson->get("foo").extract<string>();                   // Specify type as string
        auto       data_pjarray     = json_pocojson->get("data").extract<Poco::JSON::Array::Ptr>();  // Specify type as Json array
        auto       item_0           = data_pjarray->getObject(0);
        auto       item_1           = data_pjarray->getObject(1);
        assert    (foo_string                     == "bar");
        assert    (item_0->getValue<int64_t>("t") == 1111);
        assert    (item_1->getValue<int64_t>("t") == 2222);
        assert    (item_0->getValue<int64_t>("p") == 11);
        assert    (item_1->getValue<int64_t>("p") == 22);
    }


    void example_loop_over_array (){
        Parser     parser;
        string     json_string      = R"(  {"data":[{"p":11,"t":1111},{"p":22,"t":2222}],"foo":"bar"}  )";
        auto       json_pocojson    = parser.parse(json_string).extract<Poco::JSON::Object::Ptr>(); // Specify type as Json
        auto       data_pjarray     = json_pocojson->get("data").extract<Poco::JSON::Array::Ptr>(); // Specify type as Json array
        stack<int> t;
        stack<int> p;

        t.push(2222);
        t.push(1111);
        p.push(22);
        p.push(11);
        // The Poco JSON array is not a C11 range, so a range-base for loop errors on compile with
        //      this range-based 'for' statement requires a suitable "begin" function and none was foundC/C++(2291)
        // The pre-range method is the only option
        for (auto item_pjaiterator = data_pjarray->begin(); item_pjaiterator != data_pjarray->end(); ++item_pjaiterator) {
        auto item_pocojson = item_pjaiterator->extract<Poco::JSON::Object::Ptr>();
        assert (item_pocojson->get("t").extract<int64_t>() == t.top()); t.pop();
        assert (item_pocojson->get("p").extract<int64_t>() == p.top()); p.pop();
        }
    }


    int main() {
        cout << "This is json-array-poco\n";
        example_index_into_array();
        example_loop_over_array();

        return 0;
    }
Unclad answered 29/12, 2023 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.