Sub topic 10
Swapping formats without changing your types
This chapter assumes you can derive Serialize and Deserialize, and that you have used serde_json to round-trip a struct. Here you will reuse one type with a second format.
Why the types stay the same
Your derived code never mentions JSON. It talks to the serde data model through a Serializer or Deserializer. Each format crate supplies its own implementation of those traits. The type you wrote is therefore not tied to any format.
Adding the toml crate
Add toml next to the dependencies you already have.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"One struct, two formats
The struct below has no format-specific code. The same value is written as JSON and as TOML, and the TOML text is read back.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Settings {
name: String,
port: u16,
debug: bool,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let settings = Settings {
name: "api".to_string(),
port: 8080,
debug: true,
};
let as_json = serde_json::to_string(&settings)?;
let as_toml = toml::to_string(&settings)?;
println!("{as_json}");
println!("{as_toml}");
let back: Settings = toml::from_str(&as_toml)?;
println!("{back:?}");
Ok(())
}The program prints this:
{"name":"api","port":8080,"debug":true}
name = "api"
port = 8080
debug = true
Settings { name: "api", port: 8080, debug: true }The function names follow a pattern across crates: to_string and from_str for text formats, and usually to_vec and from_slice for binary ones. Some crates use different names, so check each crate's documentation.
The same attributes apply
Attributes such as rename_all, default, and skip live on your type, so they work in every format. A struct marked #[serde(rename_all = "camelCase")] uses camelCase keys in JSON and in TOML. Attributes that depend on format features are the exception, as the next section shows.
Where formats differ
The data model is shared, but each format can represent only part of it. Errors show up at runtime, not at compile time.
| Format | Limit you may hit |
|---|---|
| TOML | No null value. The top level must be a table, so a bare number or list cannot be serialized. Integers are stored as 64-bit signed values, so a `u64` above `i64::MAX` fails. |
| JSON | Map keys must be strings or something serde can turn into a string. A map keyed by a struct fails. |
| bincode and other binary formats | The format is not self-describing. The bytes do not say what type they hold. |
The last row matters most. A non-self-describing format cannot read data without knowing the exact type. These features rely on inspecting the data and are therefore unreliable or unsupported there:
#[serde(untagged)]enums- internally tagged enums
#[serde(flatten)]skip_serializing_if, because skipped fields shift the positions of the remaining ones
If you plan to use a binary format, avoid these attributes on the types it handles.
Picking a crate
Choose the crate for the target. toml suits configuration files. ron suits Rust-flavored text data. bincode and postcard give compact binary output. Check that the crate is maintained before adopting it, since some serde format crates have been archived or deprecated.
Exercise
You add #[serde(flatten)] to a struct and it works with serde_json. A teammate then tries to encode the same struct with bincode and gets an error. Why does the format matter here, and what are two ways to resolve it?
Show answer
Flatten needs to look at the keys in the data to decide which fields belong where. bincode is not self-describing, so it has no keys to inspect. You can remove flatten from the type used with bincode, for example by using an explicit nested struct, or you can use a self-describing format for that data.