我想使用Serde从github上Bowserinator的库反序列化元素周期表的JSON文件。为此,我创建了一个拥有所有必要字段的结构并派生了所需的宏:
#[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,
}
这个方法在遇到包含“null”值的字段时会出现问题。例如,在Helium中,对于字段"color": null
。
我收到的错误消息是{ code: Message("invalid type: unit value, expected a string"), line: 8, column: 17 }
,针对此字段。
我尝试使用#[serde(default)]
宏进行实验。但是,当JSON文件中存在null
值时,它仅适用于字段缺失的情况。
我希望能够使用标准宏进行反序列化,而不是编写Visitor Trait。是否有我忽略的技巧?
Option
和Result
的概念,这在Rust中非常普遍。(链接) - Shepmaster