如何解码可以是 String 或 null 的 JSON 值?

How to decode a JSON value that can be a String or null?

我正在尝试用 Rust 解码 JSON。

JSON 例子:

[{"id": 1234, "rank": 44, "author": null}]
[{"id": 1234, "rank": 44, "author": "Some text"}]

如果作者字段使用 String

#[derive(Show, RustcDecodable, RustcEncodable)]
pub struct TestStruct {
    pub id: u64,
    pub rank: i64,
    pub author: String,
}

它抛出错误:

thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: ExpectedError("String", "null")', /home/rustbuild/src/rust-buildbot/slave/nightly-dist-rustc-linux/build/src/libcore/result.rs:742

如何解码(filter/ignore null)这个 JSON 值?

author 的类型从 String 更改为 Option<String>

#[derive(Show, RustcDecodable, RustcEncodable)]
pub struct TestStruct {
    pub id: u64,
    pub rank: i64,
    pub author: Option<String>,
}

结果:

Ok([TestStruct { id: 1234u64, rank: 44i64, author: None }]
Ok([TestStruct { id: 1234u64, rank: 44i64, author: "Some text" }])