反序列化包含不同类型对象的 JSON 数组

Jou*_*las 5 json rust serde

所以我有一个如下所示的 JSON:

{
  "name": "customer",
  "properties": [
    {
      "name": "id",
      "type": "int",
      "value": 32
    },
    {
      "name": "name",
      "type": "string",
      "value": "John"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

目前我正在反序列化到这组结构:

#[derive(Serialize, Deserialize, Debug)]
struct Customer {
    name: String,
    properties: Vec<Property>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "name", content = "value")]
enum Property {
    #[serde(rename = "id")]
    Id(i32),
    #[serde(rename = "name")]
    Name(String),
}
Run Code Online (Sandbox Code Playgroud)

但为了避免每次我想访问一个属性时都要处理枚举匹配,我想将其反序列化为如下所示的结构:

struct Customer {
  name: String,
  properties: Properties,
}

struct Properties {
  id: i32, // will be 32 as in the object containing the name "id".
  name: String, // will be John as in the object containing the name "name".
}
Run Code Online (Sandbox Code Playgroud)

这是serde图书馆以某种方式允许的吗?如果是这样,您能提供一个如何实现这一目标的例子吗?

请注意,我不能弄乱实际的 json 结构,所以我对任何需要它的解决方案不感兴趣。

Jou*_*las 1

感谢edkeveked 的回答,我设法找到了一个非常适合我的需求的解决方案。

基本上,我重新安排了反序列化器以循环整个属性数组,并尝试将其中的每个对象与枚举变体相匹配。我喜欢这个,因为我可以在将来轻松映射新的属性,并且它在类型方面感觉更灵活。

无论如何,这是它的代码:

extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;

use serde::de::{Deserializer, SeqAccess, Visitor};
use std::fmt;

#[derive(Serialize, Deserialize, Debug)]
struct Customer {
    name: String,
    #[serde(deserialize_with = "parse_property")]
    properties: CustomerProps,
}

#[derive(Default, Serialize, Deserialize, Debug)]
struct CustomerProps {
    id: i32,
    name: String,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "name", content = "value")]
enum Property {
    #[serde(rename = "id")]
    Id(i32),
    #[serde(rename = "name")]
    Name(String),
}

fn parse_property<'de, D>(deserializer: D) -> Result<CustomerProps, D::Error>
where
    D: Deserializer<'de>,
{
    struct PropertyParser;
    impl<'de> Visitor<'de> for PropertyParser {
        type Value = CustomerProps;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("[u64, f32, usize]")
        }

        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
            let mut prop = CustomerProps {
                ..Default::default()
            };
            while let Some(tmp) = seq.next_element::<Property>()? {
                match tmp {
                    Property::Id(id) => prop.id = id,
                    Property::Name(name) => prop.name = name,
                }
            }
            Ok(prop)
        }
    }
    deserializer.deserialize_any(PropertyParser {})
}

fn main() {
    let data = r#"{
        "name": "customer",
        "properties": [
            {
                "name": "id",
                "type": "int",
                "value": 32
            },
            {
                "name": "name",
                "type": "string",
                "value": "John"
            }
        ]
    }"#;

    let p: Customer = serde_json::from_str(data).unwrap();

    println!("Please call {} at the number {} {}", p.name, p.properties.id, p.properties.name);
}
Run Code Online (Sandbox Code Playgroud)