Hi,
I have a JSON file something like this.
{
"name" : "S.Gopinath",
"city: : "Chennai",
"cell": "9x380x414x30",
"own_aircraft" : null
}
I want to use serde_json to deserialize in to a struct.
My struct could be as following.
struct myself {
name : String,
city : String,
cell : String,
own_aircraft : ???
//Should I use enum Option ?
}
ow to accept the values for "null" which is supported as a type in JSON ?
Should I use Option type in the struct definition ?
Option<YourAircraftType>
is usually the way to go.
If you want to avoid Option
, then the alternative is to add #[serde(default)]
annotation to replace missing fields with their default values.
https://serde.rs/attr-default.html
This is handy if a field is Vec
and you'd rather get an empty vec than deal with Option<Vec>
.
2 Likes
Okay.. it works as I use Option.
struct myself {
name : String,
city : String,
cell : String,
own_aircraft : Option<String>,
}
Does it mean that when serde_json encounters null , it sets None for
own_aircraft and Some if it counters String ?
Right ?
Thanks,
S.Gopinath
I don't think default
works (without keeping Option) if there is an explicit null
entry in the JSON.
system
Closed
7
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.