簡體   English   中英

如何實現反序列化和派生它

[英]How to both implement deserialize and derive it

我有一個struct Foo ,我想將它序列化為 JSON 中的單個兩部分字符串,例如"01abcdef:42" ,但在 bincode 中是正常的。

(由於大小的原因,我需要在 bincode 中正常序列化它。在某些情況下, BarBaz是大的 arrays 字節,占用了十六進制空間的兩倍以上。)

我當前的代碼正是我想要的:

pub struct Foo {     
        pub bar: Bar,
        pub baz: Baz
}

impl<'de> ::serde::Deserialize<'de> for Foo {
        fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Foo, D::Error> {
                use ::serde::de::Error;
                use core::str::FromStr;

                if d.is_human_readable() {
                        let sl: &str = ::serde::Deserialize::deserialize(d)?;
                        Foo::from_str(sl).map_err(D::Error::custom)
                } else {
                        let clone: FooClone = FooClone::deserialize(d)?;
                        Ok(Foo { bar: clone.bar, baz: clone.baz })
                }
        }
}

#[derive(Deserialize)]
pub struct FooClone {           
        pub bar: Bar,
        pub baz: Baz
}

我需要手動將FooClone維護為Foo的相同副本。

我已閱讀內容,但與此結構克隆相比,要維護的代碼要多得多。

我怎樣才能既手動實現Deserialize (處理 JSON 兩部分字符串)又為同一個結構派生Deserialize (以消除FooClone )?

像這樣的東西應該工作。 您仍然使用派生來生成deserialize化 function。 但由於它是遠程派生類型,因此不會實現Deserialize ,而是獲得固有的 function,您可以在手動Deserialize實現中調用它。

#[derive(serde::Deserialize)]
#[serde(remote = "Self")]
pub struct Foo {
    pub bar: Bar,
    pub baz: Baz,
}

impl<'de> ::serde::Deserialize<'de> for Foo {
    fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Foo, D::Error> {
        use ::serde::de::Error;
        use core::str::FromStr;

        if d.is_human_readable() {
            let sl: &str = ::serde::Deserialize::deserialize(d)?;
            Foo::from_str(sl).map_err(D::Error::custom)
        } else {
            Foo::deserialize(d)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM