簡體   English   中英

使用 serde_json 將內部枚舉值從 &str 反序列化為 u64

[英]Deserialize inner enum value from &str to u64 with serde_json

我希望能夠在 json 對象中將顏色編寫為十六進制,然后將其反序列u64我的 enum Color類型u64的內部值。

目前我有一個看起來像這樣的枚舉:

#[derive(Deserialize, Serialize)]
pub enum Color {
   Red,
   Green,
   Blue,
   Custom(u64)
}

然后我在一個看起來像這樣的結構中使用它:

pub struct Config {
    #[serde(rename = "borderColor", deserialize_with = "color_deserialize")]
    pub border_color: Color,
}

自定義反序列化功能:

fn color_deserialize<'de, D>(desierializer: D) -> Result<Color, D::Error> 
where
    D: Deserializer<'de>
{
    use serde::de::Error;
    let col = match Color::deserialize(desierializer) {
        Ok(col) => col,
        Err(e) => return Err(format!("Failed to deserilize color: {}", e)).map_err(Error::custom)
    };

    match col {
        Color::Custom(x) => {
            let x_str = &x.to_string();
            let without_prefix = x_str.trim_start_matches("#");
            let res = match u64::from_str_radix(without_prefix, 16) {
                Ok(res) => res,
                Err(e) => return Err(format!("Failed to deserialize color: {}", e)).map_err(Error::custom)
            };
            Ok(Color::Custom(res))
        },
        x => Ok(col)
    }  
}

我現在對問題的理解是,在我嘗試將其轉換為十進制之前,派生的Deserialize首先根據枚舉的類型(即 u64)映射 json 值。 因此,因此如果 json 表示是字符串而不是數字,它將中斷。

如何使用u64的內部類型保留我的變體,但在 json 中將顏色表示為十六進制?

您可以自定義Color本身的反序列化:

use serde::{de, Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug)]
pub enum Color {
    Red,
    Green,
    Blue,
    #[serde(deserialize_with = "color_deserialize")]
    Custom(u64),
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Config {
    #[serde(rename = "borderColor")]
    pub border_color: Color,
}

fn color_deserialize<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
    D: de::Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    let without_prefix = s.trim_start_matches("#");
    match u64::from_str_radix(without_prefix, 16) {
        Ok(res) => Ok(res),
        Err(e) => Err(de::Error::custom(format!(
            "Failed to deserialize color: {}",
            e
        ))),
    }
}

fn main() {
    let c = serde_json::from_str::<Config>(
        r##"{ "borderColor": { "Custom": "#bdcebe" }}"##,
    );
    println!("{:#?}", c);
}

當然,您還必須實現另一半,即序列化。

暫無
暫無

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

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