Skip to content
rusthacks.dev
Rust

Serializing and Deserializing JSON in Rust With Serde JSON

Turn Rust structs into JSON and back with serde and serde_json, including renames, optional fields, defaults and what the parse errors look like.

2 min read
Summarize in AI
Flat illustration for the post “Serializing and Deserializing JSON in Rust With Serde JSON”, composed around ownership.

Most Rust services read and write JSON, and the work should be a derive and two function calls. Serde's design makes that true: the data structure and the format are separate, so your struct knows nothing about JSON. This post gets you from a struct to a string and back, then covers the four attributes that handle real payloads.

Everything runs on Rust 1.90 with serde 1 and serde_json 1.

Add the crates

Cargo.tomlTOML
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Serialize a struct

src/main.rsrust
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct User {
    user_id: u64,
    display_name: String,
    email: Option<String>,
    #[serde(default)]
    tags: Vec<String>,
}

fn main() -> Result<(), serde_json::Error> {
    let user = User {
        user_id: 7,
        display_name: "Ana".to_string(),
        email: None,
        tags: vec!["admin".to_string()],
    };
    let json = serde_json::to_string(&user)?;
    println!("{json}");

    let back: User = serde_json::from_str(&json)?;
    println!("{back:?}");
    Ok(())
}

The first line printed is {"userId":7,"displayName":"Ana","email":null,"tags":["admin"]}. None serializes as null, which some APIs dislike; add #[serde(skip_serializing_if = "Option::is_none")] to drop the key instead. to_string_pretty formats with indentation.

Deserialize with real-world gaps

rust
let text = r#"{"userId": 8, "displayName": "Bo"}"#;
let user: User = serde_json::from_str(text)?;

email is Option, so the missing key becomes None. tags has default, so it becomes an empty vector. Without either attribute the same input fails with:

Text
missing field `tags` at line 1 column 34

What the errors say

Type mismatches name the line and column:

Text
invalid type: string "7", expected u64 at line 1 column 14

Serde never guesses, so a numeric string stays a string. Fixing it belongs in the producer, or in a deserialize_with function if you cannot change it.

Unknown shapes

For JSON you only partly control, parse into a dynamic value:

rust
let v: serde_json::Value = serde_json::from_str(r#"{"a": [1, 2, 3]}"#)?;
println!("{}", v["a"][1]);

That prints 2. Indexing a missing key yields Value::Null and not a panic. Use Value at the edge, then convert to typed structs as early as possible; see parse, don't validate for why.

Errors and the question mark

serde_json::Error implements std::error::Error, so it composes with the approach in anyhow versus thiserror. In a web handler, a parse error should become a 400; that mapping is covered in JSON requests and responses in Axum.

When this is not enough

Enums, flattened structs and untagged unions each need their own attributes, and binary or very large data want other formats. The Serde documentation explains every attribute, and serde_json on docs.rs covers streaming and RawValue.

Also inWeb
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.