我正在尝试解析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值?
答案 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" }])