pub fn deserialize_number_from_string<'de, T, D>(
deserializer: D,
) -> Result<T, D::Error>
Expand description
Deserializes a number from string or a number.
§Example:
use serde_aux::prelude::*;
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyStruct {
#[serde(deserialize_with = "deserialize_number_from_string")]
number_from_string: u64,
}
let s = r#" { "number_from_string": "123" } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.number_from_string, 123);
let s = r#" { "number_from_string": 444 } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.number_from_string, 444);
For making it work with strong types you must implement FromStr
trait. It is quite simple.
§Example
use std::str::FromStr;
use std::num::{ParseIntError, ParseFloatError};
use serde_aux::prelude::*;
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
struct IntId(u64);
impl FromStr for IntId {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<IntId, Self::Err> {
Ok(IntId(u64::from_str(s)?))
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct MyStruct {
#[serde(deserialize_with = "deserialize_number_from_string")]
int_id: IntId,
}
let s = r#"{ "int_id": "123" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.int_id.0, 123);
let s = r#"{ "int_id": 444 }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.int_id.0, 444);