serde_aux::field_attributes

Function deserialize_string_from_number

Source
pub fn deserialize_string_from_number<'de, D>(
    deserializer: D,
) -> Result<String, D::Error>
where D: Deserializer<'de>,
Expand description

Deserializes string from a number. If the original value is a number value, it will be converted to a string.

ยงExample:

use serde_aux::prelude::*;

#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyStruct {
    #[serde(deserialize_with = "deserialize_string_from_number")]
    number_as_string: String,
}

let s = r#" { "number_as_string": "foo" } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.number_as_string, "foo");

let s = r#" { "number_as_string": -13 } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.number_as_string, "-13");

let s = r#" { "number_as_string": 24.0034 } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.number_as_string, "24.0034");