2

下面是一个不起作用的代码示例:

use serde_json::json;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Model<T>
where
    T: DeserializeOwned,
{
    pub id: i32,
    pub info: Option<T>,
}

fn main() {
    #[derive(Serialize, Deserialize, Debug, Clone)]
    struct Info {
        name: String,
    }

    let some_model_1: Model<Info> = serde_json::from_value(json!({
        "id": 43,
        "info": {
            "name": "some_model_name"
        }
    }))
    .unwrap();

    println!("some_model_1: {:#?}", some_model_1);

    let some_model_2: Model<Info> = serde_json::from_value(json!({
        "id": 43
    }))
    .unwrap();

    println!("some_model_2: {:#?}", some_model_2);
}

错误如下:cannot satisfy 'T: Deserialize<'de>

所以我补充说:

#[serde(deserialize_with = "Option::deserialize")]
pub info: Option<T>,

现在代码可以编译,但是尽管使用了 Option 类型,但缺少的“info”对象some_model_2会导致错误:

thread 'main' panicked at 'called 'Result::unwrap()' on an 'Err' value: Error("missing field 'info'", line: 0, column: 0)', src\main.rs:34:6

我的最后一个解决方案是使用自定义函数对info字段进行反序列化:

use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
use serde_json::{json, Value};

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Model<T>
where
    T: DeserializeOwned,
{
    pub id: i32,

    #[serde(deserialize_with = "ok_or_none")]
    pub info: Option<T>,
}

fn ok_or_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    let v = Value::deserialize(deserializer)?;
    Ok(T::deserialize(v).ok())
}

fn main() {
    #[derive(Serialize, Deserialize, Debug, Clone)]
    struct Info {
        name: String,
    }

    let some_model_1: Model<Info> = serde_json::from_value(json!({
        "id": 43,
        "info": {
            "name": "some_model_name"
        }
    }))
    .unwrap();

    println!("some_model_1: {:#?}", some_model_1);

    let some_model_2: Model<Info> = serde_json::from_value(json!({
        "id": 43
    }))
    .unwrap();

    println!("some_model_2: {:#?}", some_model_2);
}

这种变化没有帮助,同样的恐慌错误仍然存​​在。该ok_or_none函数甚至没有被调用。

以下是我的依赖项:

serde = { version = "1.0.94", features = ["derive"]  }
serde_json = "1.0.40"

我不知道我还能做些什么来完成这项工作。

预先感谢您的帮助!

4

1 回答 1

3

你不需要使用DeserializeOwned,一个简单T的就足够了,当从 serde 派生时,它会检查你的属性是否可以序列化/反序列化:

use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Model<T> {
    pub id: i32,
    pub info: Option<T>,
}

fn main() {
    #[derive(Serialize, Deserialize, Debug, Clone)]
    struct Info {
        name: String,
    }

    let some_model_1: Model<Info> = serde_json::from_value(json!({
        "id": 43,
        "info": {
            "name": "some_model_name"
        }
    }))
    .unwrap();

    println!("some_model_1: {:#?}", some_model_1);

    let some_model_2: Model<Info> = serde_json::from_value(json!({
        "id": 43
    }))
    .unwrap();

    println!("some_model_2: {:#?}", some_model_2);
}

操场

于 2022-01-19T16:40:22.147 回答