[][src]Module serde_strz::opt

A (de)serializer for anything that has implemented FromStr / Display (as ToString) but does not have Serialize/Deserialize, and is wrapped in an Option type.

Example

use std::net::IpAddr;

/// A structure with an optional IP address.
#[derive(Serialize, Deserialize)]
struct WithIp {
	#[serde(with = "serde_strz::opt")]
	ip: Option<IpAddr>,
}

use serde_json::{
	from_str,
	to_string,
};
let with_ip: WithIp = from_str(r#"{"ip": "127.0.0.1"}"#)?;
assert_eq!(with_ip, WithIp { ip: Some([127, 0, 0, 1].into()) });
assert_eq!(to_string(&with_ip)?, r#"{"ip":"127.0.0.1"}"#);
let with_ip: WithIp = from_str(r#"{"ip": null}"#)?;
assert_eq!(with_ip, WithIp { ip: None });
assert_eq!(to_string(&with_ip)?, r#"{"ip":null}"#);

Combined with #[serde(default)], it allows fields to be omitted from input entirely.

/// A structure with an optional IP address that might not exist in the input.
#[derive(Serialize, Deserialize)]
struct WithIp {
	#[serde(with = "serde_strz::opt", default)]
	ip: Option<IpAddr>,
}

let with_ip: WithIp = from_str("{}")?;
assert_eq!(with_ip, WithIp { ip: None });
assert_eq!(to_string(&with_ip)?, r#"{"ip":null}"#);

let with_ip_some: WithIp = from_str(r#"{"ip": "127.0.0.1"}"#)?;
assert_eq!(with_ip_some, WithIp { ip: Some([127, 0, 0, 1].into()) });
assert_eq!(to_string(&with_ip_some)?, r#"{"ip":"127.0.0.1"}"#);

Skipping is also easy:

/// A structure with an optional IP address that might not exist in the input, and won't exist
/// in the output if it's empty.
#[derive(Serialize, Deserialize)]
struct WithIp {
	#[serde(with = "serde_strz::opt", default, skip_serializing_if = "Option::is_none")]
	ip: Option<IpAddr>,
}

let with_ip_empty: WithIp = from_str("{}")?;
assert_eq!(with_ip_empty, WithIp { ip: None });
assert_eq!(to_string(&with_ip_empty)?, "{}");

Functions

deserialize

Deserialize function, see mod docs examples to see how to use it

serialize

Serialize function, see mod docs examples to see how to use it