Expand description

Deserialize from bytes or string

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

Converting to serde_as

The same functionality can be more clearly expressed via BytesOrString and using the serde_as macro.

#[serde_as]
#[derive(Deserialize)]
struct A {
    #[serde_as(as = "BytesOrString")]
    bos: Vec<u8>,
}

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 a 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 a Vec<u8> from either bytes or string