iterate and retrieve nested object in JSON using rapidjson

后端 未结 5 1588
情书的邮戳
情书的邮戳 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 07:56

    I was wondering the same very recently, here is what i got :

    #include "rapidjson\filereadstream.h"
    #include "rapidjson\document.h"
    #include "rapidjson\istreamwrapper.h"
    #include 
    #include 
    
    using namespace rapidjson;
    
    // Documentation : using file stream instead of C FILE pointers
    // http://rapidjson.org/md_doc_stream.html#FileStreams
    ifstream file_stream(filepath);
    IStreamWrapper isw(file_stream);
    
    Document doc;
    doc.ParseStream(isw);
    file_stream.close();
    
    if(doc.HasMember(CONF_NODE)){
    Value *config_node = &(doc[CONF_NODE]);
    // Now I can use it like so:
    std::cout << (*config_node)["My Other Json node"].GetString() << std::endl;
    }
    

    I used this trick several times to avoid using unterminably long accessing request like

     doc["Node1"]["Node2"]["Node3"]...["NodeX"].GetType() 
    and instead rely on pointers that could be used to virtually "split" the doc chain:

    doc["Node1"]["Node2"]["Node3"]...["NodeX"].GetType()
                         |            |
                     pointer1         |
                                      pointer2
    (*pointer_on_Node_N)["Node N+1"] = doc["Node1"][...]["NodeN"]["Node N+1]
    

    That was particularly handy when I needed to iterate over my file (when facing arrays).

提交回复
热议问题