#Serde deserialize mixed formats

6 messages · Page 1 of 1 (latest)

tulip bay
#

I need to deserialize URL query parameters like ?some_var=a&special={"other_var"%3A"something"} with JSON mixed in
Corresponding structs are

struct Outer {
  some_var: String,
  special: Inner
}

struct Inner {
  other_var: String
}

What's the best way to do this? I think serde's with attribute could help, but I'm not sure where to hook it up to

lethal idol
#

with allows you to write custom functions for deserialization so shouldn't be too hard to wire one up with serde_json

#

note that it's possible you'll have to take care of URL-decoding

tulip bay
lethal idol
#
fn my_deser<'de, D: Deserializer<'de>, Inner>(de: D) -> Result<Inner, D::Error> {
  let s = String::deserialize(de)?;

  // can't remember exactly but there's a "custom" constructor for errors in serde
  serde_json::from_str(&s).map_err(|_| serde::Error::custom())
}

#[derive(Deserialize)]
struct Outer {
  some_var: String,
  #[serde(deserialize_with = "my_deser")]
  special: Inner
}
#

^ not tested but smth like that