iterate and retrieve nested object in JSON using rapidjson

后端 未结 5 1586
情书的邮戳
情书的邮戳 2021-01-12 07:20

I am parsing a JSON structure which is similar as follows

{
    \"item1\" : \"value1\"
    \"item2\" : \"value2\"
    // ...
    \"itemn\" : {
          


        
5条回答
  •  清酒与你
    2021-01-12 08:00

    First, let me provide credit to MiloYip at this link

    Second-- here's what I did for my project:

    rapidjson::Document document;
    // document holds a json document retrieved from a http GET request
    // I did not include all of that in this example.  I am only showing
    // the part of iterating through a nested object and retrieving members.
    
    std::vector symbols;
    // holds the values I retrieve from the json document
    
    if (document.Parse<0>( symbol.c_str() ).HasParseError() )
        Log() << "ERROR: encountered a JSON parsing error" << std::endl;
    else {
        // Get the nested object that contains the elements I want.
        // In my case, the nested object in my json document was results
        // and the values I was after were identified as "t"
        rapidjson::Value& results = document["results"];
        assert(results.IsArray());
        for (rapidjson::SizeType i = 0; i < results.Size(); i++) {
            // Store the value of the element in a vector.
            symbols.emplace_back(results[i]["t"].GetString());
    }                            
    

    I think this is a pretty clean/efficient approach.

提交回复
热议问题