问题
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