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

时间:2015-01-19 04:07:36

标签: json deserialization rust

我正在尝试解析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

如何解码(过滤/忽略null)此JSON值?

1 个答案:

答案 0 :(得分:4)

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" }])
相关问题