Search code examples
c++rapidjson

How to get a "node" parsing a file with Rapidjson?


I'm using Rapidjson to retrieve data from a file, and I want to use that file data to create entities in my game. So, my file has the definition of what a certain entity is (in this case, each ship parameters and components to be created). File looks like follows (for a single ship called dreadnought):

{
    "dreadnought" : {
        "parameters": {
            "image": "data/dreadnought/dreadnought_ship.png",
            "linearSpeed" : 10,
            "angularSpeed" : 20,
            "energy" : 20,
            "hitpoints" : 50
        },
        "components" : {
            "primaryWeapon" : {
                "name" : "fusionBlaster",
                "energyConsumed" : 2,
                "cooldown" : 5
            },
            "secondaryWeapon" : {
                "name" : "laserBots",
                "energyConsumed" : 2,
                "cooldown" : 5
            },
            "ai" : {
                "name" : "dreadnoughtAI"
            }
        }
    }
}

What I want is to get "dreadnought" as an object into a variable, so then I can keep querying over this variable. Something similar to what you do when parsing an XML with Rapidxml:

xml_document<> doc;
doc.parse<0>((char*)buffer.ToCString());
xml_node<>* rootNode = doc.first_node();

xml_node<>* innerNode = rootNode->first_node("x");

What I can't get is that innerNode. I would want something like:

rapidjson::Object dreadnought;
dreadnought.HasMember("parameters");
...

I've tried to create an object this way, but I can't find what should I put inside template, and I don't even know if this GenericObject is what I need:

rapidjson::GenericObject<false, typename ValueT> dreadnought = m_doc["dreadnought"].GetObject();

Thanks in advance.


Solution

  • Okay, I've casually found something which can work for now, although I still have to check if it is enough for what I want.

    const rapidjson::Value &dreadnought = m_doc["dreadnought"];
    
    for (rapidjson::Value::ConstMemberIterator itr = dreadnought.MemberBegin();
    itr != dreadnought.MemberEnd(); ++itr) {
        std::cout << "name : " << itr->name.GetString() << std::endl;
    }
    

    This way, each time I call the function which contains that code, it shows:

    name : parameters
    name : components
    

    So this is what I wanted.