How to deserialize a subfield of a struct from the original struct's JSON with Serde?

Viewed 2057

I want to have the Test::team_size attribute be deserialized from the data of Test object itself:

#[derive(Debug, Serialize, Deserialize)]
struct TeamSize {
    pub min: i64,
    pub max: i64,
}

#[derive(Debug, Serialize, Deserialize)]
struct Test {
    pub i: i64,
    pub team_size: TeamSize,
}

fn main() {
    let t: Test = serde_json::from_str(r#"{"i": -2, "min": 2, "max": 5}"#).unwrap();
    assert_eq!(t.i, -2);
    assert_eq!(t.team_size.min, 2);
    assert_eq!(t.team_size.max, 5);
}

This code does not compile and I don't know how to make Serde do what I want. Is there a way to deserialize team_size in this example from the JSON of the original structure where it is a subfield?

It seems that I want something like #[serde(untagged)] but for a struct and for a field and not the whole struct.

2 Answers
Related