serde_aux::field_attributes

Function deserialize_vec_from_string_or_vec

Source
pub fn deserialize_vec_from_string_or_vec<'de, T, D>(
    deserializer: D,
) -> Result<Vec<T>, D::Error>
where D: Deserializer<'de>, T: FromStr + Deserialize<'de> + 'static, <T as FromStr>::Err: Display,
Expand description

Deserializes a comma separated string into a Vec<T>.

ยงExample:

use serde_aux::prelude::*;

#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyStruct {
    #[serde(deserialize_with = "deserialize_vec_from_string_or_vec")]
    list: Vec<i32>,
}

let s = r#" { "list": "1,2,3,4" } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(&a.list, &[1, 2, 3, 4]);

let s = r#" { "list": [1,2,3,4] } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(&a.list, &[1, 2, 3, 4]);