Expand description
Serde module that accepts either a string or a number and coerces the
value to the target type via core::str::FromStr.
This is useful for APIs that may return "42" or 42 for the same field.
§Supported target types
Any type that implements both serde::Deserialize and
core::str::FromStr, including u64, i64, f64, bool, and any
custom newtype that wraps these.
§Examples
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Record {
#[serde(with = "api_bones::serde::maybe_string")]
count: u64,
#[serde(with = "api_bones::serde::maybe_string")]
ratio: f64,
#[serde(with = "api_bones::serde::maybe_string")]
active: bool,
}
// Numbers accepted as-is
let from_num: Record =
serde_json::from_str(r#"{"count":42,"ratio":3.14,"active":true}"#).unwrap();
assert_eq!(from_num.count, 42);
// Strings coerced to the target type
let from_str: Record =
serde_json::from_str(r#"{"count":"42","ratio":"3.14","active":"true"}"#).unwrap();
assert_eq!(from_str, from_num);Functions§
- deserialize
- Deserialize a value that may arrive as a string or a native JSON type.
- serialize
- Serialize the value using its standard
Serializeimplementation.