我正在尝试在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值?
最佳答案
将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" }])
关于json - 如何解码可以为String或null的JSON值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28017826/