[英]How to parse json file with std::optional< std::variant > type in C++?
How can I parse nested json in c++?如何在 C++ 中解析嵌套的 json? I am looking for a json parser that is capable of parsing nested json.
我正在寻找能够解析嵌套 json 的 json 解析器。 Especially this field in the example json below:
尤其是下面示例 json 中的这个字段:
optional<variant<bool, Secondary>> secondary;
It is type composition of optional
and variant
.它是
optional
和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;
};
I'd rather (ab)use 'std::monostate' as the 1st type arg for 'std::variant' than to use 'std::optional' on 'std::variant'.我宁愿(ab)使用“std::monostate”作为“std::variant”的第一种类型arg,而不是在“std::variant”上使用“std::optional”。 If the variant holds monostate, it means an empty variant.
如果变体保持单态,则意味着一个空变体。 By the way, why to reinvent the wheel while 'boost::property_tree' is available?
顺便说一句,为什么要在 'boost::property_tree' 可用时重新发明轮子?
https://www.boost.org/doc/libs/1_72_0/doc/html/property_tree.html https://www.boost.org/doc/libs/1_72_0/doc/html/property_tree.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.