Sub topic 10
Swapping formats without changing your types
This chapter assumes you can derive Serialize and Deserialize, you know the serde data model at a basic level, and you have already round-tripped a struct through serde_json. Here you will use the same types with a second format, TOML, and learn where formats differ.
Why the types stay the same
A type that derives Serialize does not know which format will receive it. It describes itself as calls into the serde data model: "a struct with these fields", "a sequence of strings", "an optional value". A format crate supplies a Serializer that turns those calls into bytes or text. On the way in, a format crate supplies a Deserializer that reads its input and drives the derived Visitor.
Both sides depend only on the data model. That is why one struct works with every format crate.
Common format crates include serde_json (JSON), toml (TOML), ciborium (CBOR), rmp-serde (MessagePack), bincode and postcard (compact binary), and csv (rows of text). Each one exposes its own entry points. There is no shared to_string trait, so the function names differ from crate to crate.
Adding a second format
Add the toml crate next to the dependencies you already have:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"The following program serializes one value to both formats, reads each result back, and checks that both round trips match the original. The struct has a nested struct and an Option field that is None.
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Limits {
max_connections: u32,
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Server {
host: String,
port: u16,
tags: Vec<String>,
proxy: Option<String>,
limits: Limits,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let server = Server {
host: "localhost".to_string(),
port: 8080,
tags: vec!["web".to_string(), "api".to_string()],
proxy: None,
limits: Limits { max_connections: 100 },
};
let as_json = serde_json::to_string(&server)?;
let as_toml = toml::to_string(&server)?;
println!("{as_json}");
println!("{as_toml}");
let from_json: Server = serde_json::from_str(&as_json)?;
let from_toml: Server = toml::from_str(&as_toml)?;
assert_eq!(from_json, server);
assert_eq!(from_toml, server);
Ok(())
}The JSON output is one line:
{"host":"localhost","port":8080,"tags":["web","api"],"proxy":null,"limits":{"max_connections":100}}The TOML output has no proxy line, and the nested struct becomes its own table:
host = "localhost"
port = 8080
tags = ["web", "api"]
[limits]
max_connections = 100The Server definition did not change between the two calls. Only the function you call changed. The Box<dyn std::error::Error> return type works with ? because the error types of both crates implement std::error::Error.
The API shape is similar, not identical
Most text-format crates follow the same naming pattern, which makes switching easy.
| Operation | `serde_json` | `toml` |
|---|---|---|
| Value to string | `to_string`, `to_string_pretty` | `to_string`, `to_string_pretty` |
| String to value | `from_str` | `from_str` |
| Bytes to value | `from_slice` | not provided, convert to `&str` first |
| Error type | `serde_json::Error` | `toml::ser::Error`, `toml::de::Error` |
Notice that toml has separate error types for each direction, and serde_json has one. Binary crates often use to_vec and from_slice or from_reader instead. Check the documentation of the crate you pick rather than assuming the names.
Choosing a format at runtime
When a program accepts several formats, wrap the differences in one function. The generic bound DeserializeOwned means the result does not borrow from the input, which is what you want when the input string is temporary.
use serde::{de::DeserializeOwned, Deserialize};
#[derive(Debug, Deserialize)]
struct Limits {
max_connections: u32,
}
enum Format {
Json,
Toml,
}
fn parse<T: DeserializeOwned>(text: &str, format: Format) -> Result<T, String> {
match format {
Format::Json => serde_json::from_str(text).map_err(|e| e.to_string()),
Format::Toml => toml::from_str(text).map_err(|e| e.to_string()),
}
}
fn main() {
let a: Result<Limits, String> = parse(r#"{"max_connections": 100}"#, Format::Json);
let b: Result<Limits, String> = parse("max_connections = 100", Format::Toml);
println!("{a:?}");
println!("{b:?}");
}Both lines print Ok(Limits { max_connections: 100 }). Converting the error to a String is a shortcut for this example. In a real program you would define an error enum with one variant per format so callers can still match on the cause.
Where formats differ
Sharing a type does not mean every format accepts every type. Each format has its own limits, and the data model passes them through without hiding them.
Representable values
TOML has no null. The toml serializer skips a None struct field, as the output above shows. A None inside an array has no place to go, so serialization returns an error. TOML also requires a table at the top level. A bare number or string passed to toml::to_string returns an error, while JSON accepts any value at the top.
Ordering matters in TOML too. Plain values must come before nested tables in the text, and the toml crate handles that when it writes the output. If you build TOML text by hand, keep that rule in mind.
Self-describing and non-self-describing formats
JSON and TOML are self-describing. The input text contains enough structure (keys, brackets, quote marks) for the deserializer to tell what comes next without being told. Compact binary formats such as bincode and postcard are not. They store values in field order with no names or type markers, and the Rust type is the only schema.
That has direct consequences for attributes you have already learned:
#[serde(untagged)]enums and internally tagged enums need to look ahead at the input. They rely on a self-describing format and fail or misbehave on non-self-describing ones.#[serde(flatten)]has the same dependency, because it buffers the input to sort keys between fields.#[serde(skip_serializing_if = "...")]breaks positional formats. The writer omits a field, and the reader expects it, so the bytes no longer line up.deny_unknown_fieldshas no meaning when the format has no field names.
If you intend to use a binary format, test that format early with the exact types you plan to ship. A type that works in JSON is not guaranteed to work in postcard.
Human-readable and compact representations
Some types serialize differently depending on the format. A Serializer reports through is_human_readable() whether it targets people or machines, and types can adapt. For example, an IP address type may write the string "127.0.0.1" for JSON and four raw bytes for a binary format. The same type, the same derive, a different encoding. If you write a manual Serialize impl for a type that has a natural text form and a natural binary form, you can branch on this method.
Numbers and keys
JSON numbers have no fixed size, but the serdejson default parser maps them into the Rust type you ask for. A value too large for the field type is an error, not a silent wrap. TOML integers are 64-bit signed, so a u64 above i64::MAX cannot be written. In JSON, object keys are strings, so `serdejson` writes integer map keys as strings and reads them back. Do not assume other formats do the same.
Maintenance of format crates
Format crates are separate projects with separate release schedules. serde_yaml was archived by its author in 2024, so check which YAML crate is currently maintained before adding one. The same check is worth doing for any format crate in a long-lived project.
A round-trip test per format
The following test serializes one value through both formats and checks equality. It is a template you can extend with each new format you support.
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Settings {
name: String,
verbose: bool,
retries: Option<u8>,
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Settings {
Settings { name: "demo".to_string(), verbose: true, retries: None }
}
#[test]
fn json_round_trip() {
let text = serde_json::to_string(&sample()).unwrap();
let back: Settings = serde_json::from_str(&text).unwrap();
assert_eq!(back, sample());
}
#[test]
fn toml_round_trip() {
let text = toml::to_string(&sample()).unwrap();
let back: Settings = toml::from_str(&text).unwrap();
assert_eq!(back, sample());
}
}
fn main() {
println!("{}", serde_json::to_string(&Settings {
name: "demo".to_string(),
verbose: true,
retries: None,
}).unwrap());
}Run cargo test to check both formats. Running cargo run prints {"name":"demo","verbose":true,"retries":null}.
Exercise
A struct has a field note: Option<String> that is None. Serializing it with serde_json::to_string writes "note":null, while toml::to_string writes no note line. Why do the outputs differ, and does deserializing the TOML back into the struct succeed?
Show answer
Both calls make the same data-model call for the field, which says the value is None. JSON has a null value, so its serializer writes null. TOML has no null, so the toml serializer leaves out a None struct field. Deserializing the TOML succeeds, because the derived Deserialize treats a missing Option field as None.
Exercise
You plan to store an enum marked #[serde(untagged)] with postcard. It works in JSON. What should you expect, and what is a safer choice?
Show answer
Expect failure. An untagged enum needs the deserializer to look ahead at the data, and postcard is not self-describing, so it cannot support that. Switch the enum to an externally tagged representation, the default, which stores a variant index that a positional format can read. Then test it with postcard directly.