jsonrustserde

How to deserialize a field that contains JSON?


Imagine I need to parse the following body:

{
  "input": "{\"type\":\"id\",\"name\":\"DNI\"}"
}

As you can see, the input field contains a JSON but in "string".

I have the following Rust struct

pub struct Input {
  input: String
}

and then I can deserialize it, but I would like to have it defined like this:

pub struct InputType {
  type: String,
  name: String
}
pub struct Input {
  input: InputType
}

any idea how can I do it?


Solution

  • Use deserialize_with like so:

    #[derive(Deserialize)]
    struct InputType {
        #[serde(rename = "type")]
        typ: String,
        name: String,
    }
    
    #[derive(Deserialize)]
    struct Input {
        #[serde(deserialize_with = "deserialize_input")]
        input: InputType,
    }
    
    fn deserialize_input<'de, D: Deserializer<'de>>(d: D) -> Result<InputType, D::Error> {
        let text = String::deserialize(d)?;
        serde_json::from_str(&text).map_err(serde::de::Error::custom)
    }
    

    Playground