Snažím sa dekódovať JSON v Rust.
Príklady JSON:
[{"id": 1234, "rank": 44, "author": null}]
[{"id": 1234, "rank": 44, "author": "Some text"}]
Ak používam String
pre autorské pole:
#[derive(Show, RustcDecodable, RustcEncodable)]
pub struct TestStruct {
pub id: u64,
pub rank: i64,
pub author: String,
}
To hodí chybu:
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
Ako môžem túto hodnotu JSON dekódovať (filtrovať / ignorovať nulu)?
odpovede:
4 pre odpoveď č. 1Zmeňte typ author
z String
na Option<String>
.
#[derive(Show, RustcDecodable, RustcEncodable)]
pub struct TestStruct {
pub id: u64,
pub rank: i64,
pub author: Option<String>,
}
výsledky:
Ok([TestStruct { id: 1234u64, rank: 44i64, author: None }]
Ok([TestStruct { id: 1234u64, rank: 44i64, author: "Some text" }])