Reputation: 1465
I am trying to decode JSON in Rust.
JSON examples:
[{"id": 1234, "rank": 44, "author": null}]
[{"id": 1234, "rank": 44, "author": "Some text"}]
If I use String
for the author field:
#[derive(Show, RustcDecodable, RustcEncodable)]
pub struct TestStruct {
pub id: u64,
pub rank: i64,
pub author: String,
}
It throws the error:
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
How can I decode (filter/ignore null) this JSON value?
Upvotes: 2
Views: 227
Reputation: 65782
Change the type of author
from String
to Option<String>
.
#[derive(Show, RustcDecodable, RustcEncodable)]
pub struct TestStruct {
pub id: u64,
pub rank: i64,
pub author: Option<String>,
}
Results:
Ok([TestStruct { id: 1234u64, rank: 44i64, author: None }]
Ok([TestStruct { id: 1234u64, rank: 44i64, author: "Some text" }])
Upvotes: 4