2

包含 Box 作为成员变量的结构:

type Item = dyn Fn() -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
struct Inner {
    pub data: Box<Item>,
}

// a function, like the type: Item
fn parse() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("parse called");
    Ok(())
}

现在出现了自定义实现反序列化以使结构反Inner序列化的问题:

let s = r#"{"data": "parse"}"#;

进入结构内部:

{
    data: Box::new(parse)
}

我知道serde不实现反序列Box<T>化,并且必须手动实现反序列化,这是我的代码遵循文档给出的示例

use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
use std::fmt;

type Item = dyn Fn() -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
struct Inner {
    pub data: Box<Item>,
}

fn parse() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("parse called");
    Ok(())
}

impl<'de> Deserialize<'de> for Inner {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            Data,
        };

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl<'de> Visitor<'de> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("`data` only")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "data" => Ok(Field::Data),
                            _ => Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct InnerVisitor;

        impl<'de> Visitor<'de> for InnerVisitor {
            type Value = Inner;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct Inner")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Inner, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut data = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Data => {
                            if data.is_some() {
                                return Err(de::Error::duplicate_field("data"));
                            }
                            data = Some(map.next_value()?);
                        }
                    }
                }
                let data = data.ok_or_else(|| de::Error::missing_field("data"))?;
                //
                // do something on the `data` and finally return a Item-like function  (***)
                //
                Ok(Inner {
                    data: Box::new(parse),
                }) // (***)
            }
        }

        const FIELDS: &'static [&'static str] = &["data"];
        deserializer.deserialize_struct("Inner", FIELDS, InnerVisitor)
    }
}

fn main() {
    let s = r#"{"data": "parse"}"#;
    let inner: Inner = serde_json::from_str(s).unwrap();
}

但是,当我运行这些代码时,会出现错误:

   Compiling playground v0.0.1 (/playground)
warning: unused variable: `inner`
  --> src/main.rs:93:9
   |
93 |     let inner: Inner = serde_json::from_str(s).unwrap();
   |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_inner`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: unused variable: `data`
  --> src/main.rs:76:21
   |
76 |                 let data = data.ok_or_else(|| de::Error::missing_field("data"))?;
   |                     ^^^^ help: if this is intentional, prefix it with an underscore: `_data`

warning: 2 warnings emitted

    Finished dev [unoptimized + debuginfo] target(s) in 1.12s
     Running `target/debug/playground`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: string \"parse\", expected unit", line: 1, column: 16)', src/main.rs:93:48
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

粗略地说,我猜问题(***)出在街区,但不知道如何解决。如何正确实施Deserialize我的用例?

4

2 回答 2

3

警告给了你一个提示:你没有使用数据,所以 Rust 不关心 Option 中的类型。实际上我很惊讶它正在编译。()由于 serdes 默认类型,Rust 假设您期望String. 您的数据根本不会被消耗,所以只需执行以下操作:

let mut data: Option<&str> = None;

另外,我建议将您的所有Field实现替换为:

#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
    Data,
}

(此堆栈在操场上因未知原因溢出,但我认为这是操场的问题)


此外,您可以只使用deserialize_with

use serde::{Deserialize, Deserializer};

type Item = dyn Fn() -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
#[derive(Deserialize)]
struct Inner {
    #[serde(deserialize_with = "deserialize_data")]
    pub data: Box<Item>,
}

fn deserialize_data<'de, D>(d: D) -> Result<Box<Item>, D::Error>
where
    D: Deserializer<'de>,
{
    let data = <&str>::deserialize(d)?;
    println!("{}", data);
    Ok(Box::new(parse))
}

fn parse() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("parse called");
    Ok(())
}

fn main() {
    let s = r#"{"data": "parse"}"#;
    let inner: Inner = serde_json::from_str(s).unwrap();
}

这要好得多,因为 serde 宏的实现可以比幼稚的实现做得更好。

于 2020-11-11T06:31:37.430 回答
2

与 Stargateurs 类似的技巧是#[serde(from = "FromType")]Inner课堂上使用。这使您可以通过实现From特征来通过中间结构。

#[derive(Deserialize)]
struct InnerRepr {
    pub data: String,
}

#[derive(Deserialize)]
#[serde(from = "InnerRepr")]
struct Inner {
    pub data: Box<Item>,
}

impl From<InnerRepr> for Inner {
  fn from(repr: InnerRepr) -> Inner {
    Inner{ data: Box::new(parse) }
  }
}
于 2020-11-11T07:45:48.170 回答