I want to deserialize the chemical elements JSON file from Bowserinator on github using Serde. For this I created a structure with all the needed fields and derived the needed macros:
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Element {
name: String,
appearance: String,
atomic_mass: f64,
boil: f64,
category: String,
#[serde(default)]
color: String,
density: f64,
discovered_by: String,
melt: f64,
#[serde(default)]
molar_heat: f64,
named_by: String,
number: String,
period: u32,
phase: String,
source: String,
spectral_img: String,
summary: String,
symbol: String,
xpos: u32,
ypos: u32,
}
This works fine until it gets to fields which contain a "null" value.
E.g. for the field "color": null,
in Helium.
The error message I get is { code: Message("invalid type: unit value, expected a string"), line: 8, column: 17 }
for this field.
I experimented with the #[serde(default)]
Macro. But this only works when the field is missing in the JSON file, not when there is a null
value.
I like to do the deserialization with the standard macros avoiding to program a Visitor Trait. Is there a trick I miss?
Option
andResult
, which are very pervasive in Rust. – Peterkin