Search code examples
jsonrustdeserialization

How to deserialize json using serde_with for double option


I am using serde_with = "2.2.0" trying to deserialize this json body:

#[derive(Deserialize, Debug)]
pub struct UpdatePartialTask {
    #[serde(
      default, // deserialization
      skip_serializing_if = "Option::is_none",// serialization
      with = "::serde_with::rust::double_option",
    )]
    pub priority: Option<Option<String>>,
    #[serde(
      default,// deserialization
      skip_serializing_if = "Option::is_none",// serialization
      with = "::serde_with::rust::double_option",
    )]
    pub user_id: Option<Option<i32>>,
    #[serde(
        default,// deserialization
        skip_serializing_if = "Option::is_none",//serialization
        with = "::serde_with::rust::double_option",
    )]
    pub title: Option<String>,
}

then I get this error:

error[E0308]: mismatched types
   --> src/routes/route_func.rs:309:10
    |
309 | #[derive(Deserialize, Debug)]
    |          ^^^^^^^^^^^ expected struct `std::string::String`, found enum `std::option::Option`
    |
    = note: expected enum `std::option::Option<std::string::String>`
               found enum `std::option::Option<std::option::Option<_>>`
    = note: this error originates in the macro `try` (in Nightly builds, run with -Z macro-backtrace for more info)

Solution

  • Thanks @kmdreko I found out that one field below my user_id field above has only one option(which should not use serde_with on this field):

    pub title: Option<String>,
    

    but it should be a double option if using with serde_with on this field:

    pub title: Option<Option<String>>,