2 releases
0.1.1 | Nov 20, 2024 |
---|---|
0.1.0 | Nov 19, 2024 |
#470 in Encoding
333 downloads per month
52KB
816 lines
serde-flexible
serde-flexible
is a Rust library that enhances the flexibility of deserialization with Serde. It is designed to handle scenarios where clients may provide input data in varying formats or make mistakes with data types. This library allows you to define custom deserialization behavior for specific fields, making it easier to work with non-standard or inconsistent data.
Features
- Flexible deserialization for fields that can accept multiple formats.
- Support for uniquely reducible types (e.g., treating integers as strings during deserialization).
- Simplifies handling of real-world data from unreliable sources.
Example
use serde::Deserialize;
use serde_flexible::{as_string, as_string_opt};
#[derive(Debug, Deserialize, PartialEq)]
struct Message {
#[serde(deserialize_with = "as_string")]
owner: String,
#[serde(deserialize_with = "as_string_opt")]
referral: Option<String>,
}
#[test]
fn test_base_good_parse() {
assert_eq!(
serde_json::from_str::<Message>(r#"{
"owner": "8a8cc628-88e3-4550-90c0-a64bd8f446dd",
"referral": 7132,
}"#).unwrap(),
Message {
owner: "8a8cc628-88e3-4550-90c0-a64bd8f446dd".to_string(),
referral: Some("7132".to_string())
}
);
}
All Possible Deserializers
Below are all the deserializers provided by serde-flexible
, along with their descriptions:
Standard Deserializers
as_bool
: Converts any input that can be interpreted as a boolean tobool
. For example,"true"
,1
, and0
can all be deserialized astrue
orfalse
.as_f64
: Converts any input that can be interpreted as a floating-point number tof64
. For example,"3.14"
will be deserialized as3.14
.as_i64
: Converts any input that can be interpreted as an integer toi64
. For example,"42"
and42
will be deserialized as42
.as_string
: Converts any input that can be interpreted as a string toString
. For example,123
will be converted to"123"
.as_u64
: Converts any input that can be interpreted as an unsigned integer tou64
. For example,"100"
and100
will be deserialized as100
.
Optional Deserializers
These deserializers allow the field to accept null
or missing values in addition to valid inputs:
as_bool_opt
: Similar toas_bool
, but also allowsnull
values, deserializing asOption<bool>
.as_f64_opt
: Similar toas_f64
, but also allowsnull
values, deserializing asOption<f64>
.as_i64_opt
: Similar toas_i64
, but also allowsnull
values, deserializing asOption<i64>
.as_string_opt
: Similar toas_string
, but also allowsnull
values, deserializing asOption<String>
.as_u64_opt
: Similar toas_u64
, but also allowsnull
values, deserializing asOption<u64>
.
Dependencies
~100–330KB