RefTryConvert

Type Alias RefTryConvert 

Source
pub type RefTryConvert<T, F = Id> = Codec<AddRef<TryInto<T, F>>, TryFrom<T, F>>;
Expand description

Adapter to serialize using TryFrom on a borrow of the source value

The adapter works by attempting a conversion from a borrow of the source value to T and serializing the result using F. When deserializing, a T is deserialized using F and converted to the source type.

§Example

use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Debug, PartialEq)]
struct StrNumber(String);

impl TryFrom<&StrNumber> for i32 {
    type Error = std::num::ParseIntError;

    fn try_from(value: &StrNumber) -> Result<Self, Self::Error> {
        value.0.parse()
    }
}

impl From<i32> for StrNumber {
    fn from(value: i32) -> Self {
        Self(value.to_string())
    }
}

#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Foo {
    #[serde(with = "serdapt::RefTryConvert::<i32>")]
    n: StrNumber,
}

let original = Foo { n: 33.into() };
let v = serde_json::to_value(&original).unwrap();
assert_eq!(v, json!({ "n": 33 }));
let deserialized = serde_json::from_value::<Foo>(v).unwrap();
assert_eq!(deserialized, original);

Aliased Type§

pub struct RefTryConvert<T, F = Id>(/* private fields */);