本文介绍了如何使用std :: optional<解析json文件std :: variant>用C ++键入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解析C ++中的嵌套json?我正在寻找一个能够解析嵌套json的json解析器.尤其是以下示例json中的此字段:

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;

它是optionalvariant的类型组成.

尽管只有完整的示例可以更清楚地揭示问题,但最小的起点示例应是以下示例:

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
          }
        }
      }
    ]

这是我已经拥有的:

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;

};

推荐答案

我宁愿(ab)将'std :: monostate'用作'std :: variant'的第一种类型arg而不是使用'std ::: 'std :: variant'上的可选".如果变量保持单态,则表示为空变量.顺便说一下,为什么在"boost :: property_tree"可用时重新发明轮子?

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

这篇关于如何使用std :: optional&lt;解析json文件std :: variant&gt;用C ++键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:20