Hello
I am trying to use the try_from
feature of serde but it is not behaving as I expected.
As you can see in my example, I want to convert JSON message containing a result
field, indicating success or not, into a Result<T>
without this result
field.
use serde::Deserialize;
use serde_json as json;
use std::convert::TryFrom;
#[derive(Deserialize, Debug)]
#[serde(try_from = "Response<Device>")]
struct Device {
model: String,
version: String,
}
#[derive(Deserialize)]
struct Response<T> {
result: String,
#[serde(flatten)]
inner: T,
}
impl TryFrom<Response<Device>> for Device {
type Error = String;
fn try_from(response: Response<Device>) -> Result<Device, String> {
if response.result == "success" {
Ok(response.inner)
} else {
Err(response.result)
}
}
}
fn main() {
let msg = r#"{
"result": "success",
"model": "foobar",
"version": "v1.0.0"
}"#;
let _: Device = json::from_str(msg).unwrap();
let msg = r#"{
"result": "error"
}"#;
let _: Device = json::from_str(msg).unwrap();
}