[][src]Module serde_with::rust::bytes_or_string

Deserialize from bytes or String

Any Rust String can be converted into bytes (Vec<u8>). Accepting both as formats while deserializing can be helpful while interacting with language which have a looser definition of string than Rust.

Example

#[derive(Debug, Deserialize, Serialize, PartialEq, Default)]
struct S {
    #[serde(deserialize_with = "serde_with::rust::bytes_or_string::deserialize")]
    bos: Vec<u8>,
}

// Here we deserialize from a byte array ...
let from = r#"{
  "bos": [
    0,
    1,
    2,
    3
  ]
}"#;
let expected = S {
    bos: vec![0, 1, 2, 3],
};

let res: S = serde_json::from_str(from).unwrap();
assert_eq!(expected, res);

// and serialization works too.
assert_eq!(from, serde_json::to_string_pretty(&expected).unwrap());

// But we also support deserializing from String
let from = r#"{
  "bos": "✨Works!"
}"#;
let expected = S {
    bos: "✨Works!".as_bytes().to_vec(),
};

let res: S = serde_json::from_str(from).unwrap();
assert_eq!(expected, res);

Functions

deserialize

Deserialize a Vec<u8> from either bytes or string