简体   繁体   中英

Parsing an action list from json using rapidjson

I'm trying to use rapidson for parsing a level definition file I have in HDD for a game.

the level definition consists on a base actions and several but different actions inside.

I'm trying to have a Factory that will create, based on the type of the action the different ones.

example json:

{
    "actions": [
        {
            "type": "load-board",
            "action": {
                "id": "level_1.1.1",
                "rows": 1,
                "columns": 1,
                "movements": 1,
                "gameBoard": [
                    0 
                ]
            }
        }
    ]
}

but it can be anything, from init-state, to move-action, to load-board.

I want to encapsulate each action into different action classes, which will execute in a std::future.

but my factory, far from what I could do in java, seems no trivial, as passing a rapidjson::GenericValue will not help as I need to pass the required parameters for the template, the .GetString() method has no proper implementation.

Have you ever implemented a delegation factory to create the different objects and actions?

this is what I was expecting to have:

std::vector<LevelAction *> * GameBoardJsonPacker::unpackLevelActionsJson(std::string json)
{
    std::vector<LevelAction *> * levelActions = new std::vector<LevelAction *>();

    rapidjson::Document document;
    document.Parse<0>(json.c_str());

    auto actions = document["actions"].GetArray();
    for(int i = 0; i < actions.Size(); i++)
    {
        levelActions->push_back(LevelActionFactory::getLevelAction(actions[i].GetString())); //here fails
    }

    return levelActions;
}

I ended up using this code to convert to const char *

apidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
document["action"].Accept( writer );
sb.GetString();

but there is no way of having a generic implementation of this GetString without modifying rapidjson code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM