4

Assume following JSON:

{
  "person": {
    "first_name": "Ala",
    "last_name": "Makota"
  }
}

Is it possible to deserialize this object to a struct like following, skipping "person"?

#[derive(Deserialize)]
struct Person {
  first_name: String,
  last_name: String,
}

It's easy to deserialize the JSON object to a wrapped struct, like this:

#[derive(Deserialize)]
struct Object {
  person: Person
}

but in my case, I'm only interested in Person structure.

EDIT:

While I'm aware that I could use serde_json's Value type to operate on JSON almost as on a Map, I'm specifically interested in the possibility of leveraging derive and maybe attributes to achieve my goal.

smbear
  • 1,007
  • 9
  • 17
  • 1
    It looks like you can solve it by using https://docs.rs/json/0.12.1/json/ – MaxV Feb 07 '20 at 23:07
  • @MaxV Seems to me that I could achieve something similar by using `serde_json`'s `Value` type. While this is something I may end up using, please see the edit of my question. – smbear Feb 08 '20 at 20:19

1 Answers1

4

Thinking the json as a map with a "person" key and a Person value it is possible to deserialize into an HashMap and then retrive the Person value.

let person = r#"
{
    "person": {
      "first_name": "Ala",
      "last_name": "Makota"
    }
  }
"#;

let deserialized = serde_json::from_str::<HashMap<&str, Person>>(&person);

The turbo fish ::<HashMap<&str, Person>> is used as a compact way to help the compiler to determine the type of deserialization.

attdona
  • 17,196
  • 7
  • 49
  • 60