rustrust-rocketserde-json

Rust Error("missing field `key`") when deserializing to JSON


I already tried this solution but it didn't work.

I always get the error Error("missing field key") and want to know how to fix this.

Code:

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
}

The id = 40:a3:cc:a3:dc:43 returns:

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

This output is correct but deserializing this String into Data gives me the error.

Data looks like this:

#[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,
}

I'm working with utoipa and rocket 0.5.


Solution

  • I fixed it by creating Data instead using 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
    }