How to parse json file with std::optional< std::variant > type in C++?

五迷三道 提交于 2020-12-30 04:20:53

问题


How can I parse nested json in c++? I am looking for a json parser that is capable of parsing nested json. Especially this field in the example json below:

optional<variant<bool, Secondary>> secondary;

It is type composition of optional and variant.

Though only the full example can surface the problem in a clearer way, a minimal starting point example would be this one:

    [
      {},
      {
        "secondary": false
      },
      {
    
        "secondary": {
          "chance": 10,
          "boosts": {
            "spd": -1
          }
        }
      },
      {
        "secondary": {
          "chance": 30,
          "volatileStatus": "flinch"
        }
      },
      {
        "secondary": {
          "chance": 30
        }
      },
      {
        "secondary": {
          "chance": 10,
          "self": {
            "boosts": {
              "atk": 1,
              "def": 1,
              "spa": 1,
              "spd": 1,
              "spe": 1
            }
          }
        }
      },
      {
        "secondary": {
          "chance": 10,
          "status": "brn"
        }
      },
      {
        "secondary": {
          "chance": 50,
          "self": {
            "boosts": {
              "def": 2
            }
          }
        }
      },
      {
        "secondary": {
          "chance": 100,
          "self": {}
        }
      },
      {
        "secondary": {
          "chance": 50,
          "boosts": {
            "accuracy": -1
          }
        }
      }
    ]

Here is what I have already:

struct Boosts {
    optional<int> atk;
    optional<int> def;
};

struct Self {
    optional<Boosts> boosts;
};
struct Secondary {
    optional<int> chance;
    optional<string> volatileStatus;
    optional<Boosts> boosts;
    optional<Self> self;
    optional<string> status;
};

struct move_t {
    int num;
    variant<bool, int> accuracy;
    int basePower;
    string category;
    optional<string> desc = std::nullopt;
    string shortDesc;
    string id;
    string name;
    optional<variant<bool, Secondary>> secondary;

};

回答1:


I'd rather (ab)use 'std::monostate' as the 1st type arg for 'std::variant' than to use 'std::optional' on 'std::variant'. If the variant holds monostate, it means an empty variant. By the way, why to reinvent the wheel while 'boost::property_tree' is available?

https://www.boost.org/doc/libs/1_72_0/doc/html/property_tree.html



来源:https://stackoverflow.com/questions/60643750/how-to-parse-json-file-with-stdoptional-stdvariant-type-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!