我有JSON,有两种形式:
public enum Avatar {
R.drawable.avatar1, R.drawable.avatar2, ..R.drawable.avatar20;
public static final Avatar values[] = values();
}
public static void main(String []args){
Drawable avatar = Avatar.values[1];//just put in the number to get the drawable
}
}
我想将它反序列化为这样的结构:
"Example:" { "field": 42, "A": 76 }
"Example:" { "field": 42, "B": 110 }
,其中
struct Example {
field: i32,
an_enum: AnEnum,
}
如果不为enum AnEnum {
A(i32),
B(i32),
}
编写自定义反序列化程序,我就不知道该怎么做。
这有效:
Example
或者,在YAML中:
"Example:" { "field": 42, "an_enum": {"A": 76} }
Example:
field: 42
an_enum:
A: 76
是多余的,写起来很烦人。如何将第一个表单反序列化为结构?或者,或者,我如何声明一个将成功反序列化我想要的语法的结构?
答案 0 :(得分:6)
您正在寻找#[serde(flatten)]
:
extern crate serde; // 1.0.75
extern crate serde_json; // 1.0.26
#[macro_use]
extern crate serde_derive; // 1.0.75
#[derive(Debug, Deserialize)]
struct Example {
field: i32,
#[serde(flatten)]
an_enum: AnEnum,
}
#[derive(Debug, Deserialize)]
enum AnEnum {
A(i32),
B(i32),
}
fn main() {
let a = r#"{ "field": 42, "A": 76 }"#;
let b = r#"{ "field": 42, "B": 110 }"#;
let a = serde_json::from_str::<Example>(a);
let b = serde_json::from_str::<Example>(b);
println!("{:?}", a);
println!("{:?}", b);
}
Ok(Example { field: 42, an_enum: A(76) })
Ok(Example { field: 42, an_enum: B(110) })
在此之前,我使用自定义反序列化:
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use serde::{Deserialize, Deserializer};
use serde::de::Error;
#[derive(Debug)]
struct Example {
field: i32,
an_enum: AnEnum,
}
#[derive(Debug)]
enum AnEnum {
A(i32),
B(i32),
}
impl<'de> Deserialize<'de> for Example {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Debug, Deserialize)]
struct Mapping {
field: i32,
#[serde(rename = "A")]
a: Option<i32>,
#[serde(rename = "B")]
b: Option<i32>,
}
let Mapping { field, a, b } = Mapping::deserialize(deserializer)?;
match (a, b) {
(Some(_), Some(_)) =>
Err(D::Error::custom("multiple variants specified")),
(Some(a), None) =>
Ok(Example { field, an_enum: AnEnum::A(a) }),
(None, Some(b)) =>
Ok(Example { field, an_enum: AnEnum::B(b) }),
(None, None) =>
Err(D::Error::custom("no variants specified")),
}
}
}
fn main() {
let a = r#"{ "field": 42, "A": 76 }"#;
let b = r#"{ "field": 42, "B": 110 }"#;
let a: Result<Example, _> = serde_json::from_str(a);
let b: Result<Example, _> = serde_json::from_str(b);
println!("{:?}", a);
println!("{:?}", b);
}