Parsing JSON with multiple representation in the same attribute

丶灬走出姿态 提交于 2019-12-01 17:33:11
Tverous

I got help from the serde-rs developer:

I would recommend using an untagged enum to represent a coordinate array that can be 2d or 3d. Playground link

Here is the code after modification:

#[derive(Serialize, Deserialize, Debug)]
struct Geometry {
    #[serde(deserialize_with = "string_or_number", rename = "type")]
    geometry_type: Value,
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "coordinates")]
    geometry_coor: Vec<Coordinates_form>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Coordinates_form {
    #[serde(skip_serializing)]
    OneD(Coordinates),
    #[serde(skip_serializing)]
    TwoD(Vec<Coordinates>),
    #[serde(skip_serializing)]
    ThreeD(Vec<Vec<Coordinates>>),
}

#[derive(Deserialize, Debug)]
struct Coordinates {
    #[serde(deserialize_with = "string_or_number")]
    longitude: Value, 
    #[serde(deserialize_with = "string_or_number")]
    latitude: Value,
}

fn string_or_number<'de, D>(de: D) -> Result<Value, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let helper: Value = Deserialize::deserialize(de)?;

    match helper {
        Value::Number(n) => {
            println!("{:#?}", n.as_f64().unwrap().to_string());
            Ok(Value::Number(n))
        }
        Value::String(s) => Ok(json!(s)),
        _ => Ok(json!(null)),
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!