反序列化为JSON时出现“ rust 错误”(“缺少字段'键'”)

hlswsv35  于 2023-03-12  发布在  其他
关注(0)|答案(1)|浏览(190)

我已经尝试了this解决方案,但它不工作.
我总是得到错误Error("missing field key"),并想知道如何修复这个问题。
代码:

pub fn get_user(id: String) -> Data  {
    let cache: RedisCache = RedisCache;

    let s: String = cache.get_str(&id).unwrap();
    println!("{}", &s);
    let user: Data = serde_json::from_str(&s).unwrap();

    user
}

id = 40:a3:cc:a3:dc:43返回:

{"change":"new","data":[],"token":"2a256356"}

此输出是正确的,但将此String反序列化为Data时出现错误。
数据如下所示:

#[derive(Serialize, Deserialize, ToSchema, Clone)]
#[serde(crate = "rocket::serde")]
pub struct Data {
    /// Device's MAC address.
    #[schema(example = "40:a3:cc:a3:dc:43")]
    pub key: String,
    /// Data from a device.
    #[schema(value_type = Object, 
        example = "{ token: 2a256356, change: new, data: [ { dns: www.google.de, mac: 40:a3:cc:a3:dc:43, src: 10.42.0.177, dst: 10.42.0.1} ] }",
    )]
    pub value: Vec<Value>,
    /// Indication whether task is done or not.
    pub done: bool,
}

我正在使用utoiparocket 0.5

1yjd4xko

1yjd4xko1#

我通过创建Data而不是使用from_str()修复了它:

pub fn get_user(id: String) -> Data  {
    let cache: RedisCache = RedisCache;

    let s: String = cache.get_str(&id).unwrap_or("Problem finding the user".to_string());
    println!("{}", &s);
    let user: Data = Data { key: id, value: vec![serde_json::json!(&s.as_str())], done: false };

    user
}

相关问题