How to Use Multiple Types for A Field in Serde JSON?

If there's no indication (besides structure) of result's type, you can use the untagged enum representation. This will try deserializing to each variant in turn until a matching one is found:

#[derive(Deserialize)]
struct GenericResponse {
    ok: bool,
    error_code: u32,
    description: String,
    result: GenericResponseResult
}

#[derive(Deserialize)]
#[serde(untagged)]
enum GenericResponseResult {
    User(User),
    // Other possible response types here...
}
7 Likes