正确使用Poco C++ JSON解析数据

iezvtpos  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(191)

有人能告诉我Poco C++ JSON是怎么工作的吗?
之前我用过JsonReader和JsonToken,Poco C++库似乎没有对应的对象。
例如,我如何使用json解析器来创建一个由标记名称处的JSON值组成的对象名称?

flvtvl50

flvtvl501#

编辑:从1.5.2开始,通过将DefaultList设置为. default(并将其重命名为正确的名称-ParseHandler),事情得到了简化。因此,如果您所需要的只是解析,则无需再显式提供处理程序:

// 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);

字符串
请参阅此答案了解更多详细信息。

yrefmtwq

yrefmtwq2#

#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

字符串

ndasle7k

ndasle7k3#

从Alex的片段(它索引到Json数组)中,我创建了一个工作示例,并在Json数组上添加了一个循环。

编译

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

字符串

需要

sudo apt install libpoco-dev


存储到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;
    }

相关问题