I am trying to deseralize some JSON that has duplicate keys and they might be in any number. The JSON looks like this:
...
"abilities": [
{
"ability_id": 5134,
"ability_level": 3
},
{
"ability_id": 5136,
"ability_level": 3
}
],
"abilities": [
{
"ability_id": 7710,
"ability_level": 4
}
]
...
And my Rust code is:
#[derive(Deserialize, Debug)]
pub struct Ancient {
score: usize,
tower_state: usize,
barracks_state: usize,
picks: Option<Vec<HeroId>>,
bans: Option<Vec<HeroId>>,
players: Vec<PlayerDetailed>,
abilities: Option<Vec<Ability>> // has many keys
}
The struct Ancient
is part of another struct that in json.
Only the last abilities
has many keys and that too in variable numbers, I have read this but am unable to change it into my liking (I want the end user to still have a struct). I have even tried #[serde(flatten)]
but it just makes everything None
. If possbile I would like to change it too:
#[derive(Deserialize, Debug)]
pub struct Ancient {
score: usize,
tower_state: usize,
barracks_state: usize,
picks: Option<Vec<HeroId>>,
bans: Option<Vec<HeroId>>,
players: Vec<PlayerDetailed>,
abilities_list: Option<abilities<Option<Vec<Ability>>>>
}
The JSON specification does not explicitly forbid duplicate keys, but most implementations will ignore all but one of them. With derived
serde::Deserialize
implementations anyserde
deserializer includingserde_json
will panic if there is a duplicate key.If you can't change the json format, you can implement
Deserialize
manually for one of your types.Let's simplify your structs and Json a little.
JSON:
And parse into structs like this:
Note that
Abilities
does not deriveDeserialize
; we'll implement it manually:Produces: