Search code examples
c++arraysdeserializationrapidjson

C++ RapidJson Help deserialize array object


I have a simple JSON doc which starts as an array and i need to parse it into a List of objects in C++. I've searched around and every thing else starts with { but my Json starts with [

I dont want to write code having to "loop" through to parse the data, it should be something very simple like ToObjectList() or ToList(), etc. It seems easy in C# with NewtonSoft, but in RapidJson C++, i cant figure this out.

Here is my JSON file....

[{
    "C": 28563.0,
    "CO": 0,
    "H": 28563.0,
    "L": 28545.0,
    "O": 28547.0,
    "T": 1562907600,
    "TO": 41315958,
    "V": 1447
}, {
    "C": 28499.0,
    "CO": 0,
    "H": 28564.0,
    "L": 28494.0,
    "O": 28563.0,
    "T": 1562911200,
    "TO": 371724821,
    "V": 13030
}, {
    "C": 28516.0,
    "CO": 0,
    "H": 28536.0,
    "L": 28481.0,
    "O": 28499.0,
    "T": 1562914800,
    "TO": 301700826,
    "V": 10582
}, {
    "C": 28539.0,
    "CO": 0,
    "H": 28545.0,
    "L": 28500.0,
    "O": 28517.0,
    "T": 1562918400,
    "TO": 150871685,
    "V": 5290
}]

Can someone help parse this is RapidJson C++ and put it in a list of Object? (preferably without having to loop through each element)

Just somehting like..... ToObjectList("json_str");


Solution

  • I will try something like this:

    Document d;
    d.Parse(yourJsonString);
    

    "d" holds the parsed JSON, so you could iterate it and append elements to your list (it could be a custom list and you could create your custom objects in each iteration):

    for (SizeType i = 0; i < d.Size(); i++) {
        // Here get elements of the array by key, build your custom object 
        // and insert it into a Vector or List
        // Example: d[i]["V"].GetInt()
    }
    

    Please, go and see this related answer too: How to parse array in root with rapidjason