Programming Search⌘K

Conceptcore

Serialization

Also called serialization, serialisation, deserialization, marshalling, unmarshalling, pickling, encoding and decoding, data serialization, object persistence.

Serialization turns values in memory into bytes or text that a file or a network can carry, and deserialization rebuilds the values. The format decides what survives the trip.

Applies to
core-languages

Idea

Values in memory are objects, pointers and structures that only one running program understands. Serialization turns them into a sequence of bytes or characters that a file, a database or a network can carry, and deserialization builds equal values from that sequence, in the same program later or in another program on another machine. The format is the contract between the two sides. It decides which types can travel, how numbers and text are written, and what is lost on the way: shared references, cycles, exact types, functions and private fields. Most bugs and attacks in this area come from a difference between what one side writes and what the other side expects.

import pickle
import struct


def dump(v, out):  # one tag byte, then the value; numbers are big-endian
    if isinstance(v, int):
        out += b"i" + struct.pack(">q", v)
    elif isinstance(v, str):
        data = v.encode()
        out += b"s" + struct.pack(">I", len(data)) + data
    elif isinstance(v, list):
        out += b"l" + struct.pack(">I", len(v))
        for x in v:
            dump(x, out)
    elif isinstance(v, dict):
        out += b"d" + struct.pack(">I", len(v))
        for k, x in v.items():
            dump(k, out)
            dump(x, out)
    else:
        raise TypeError(f"cannot serialize {type(v).__name__}")
    return out


def load(buf, i=0):  # returns the value and the index after it
    tag, i = buf[i:i + 1], i + 1
    if tag == b"i":
        return struct.unpack_from(">q", buf, i)[0], i + 8
    n, i = struct.unpack_from(">I", buf, i)[0], i + 4
    if tag == b"s":
        return buf[i:i + n].decode(), i + n
    items = []
    for _ in range(n * (2 if tag == b"d" else 1)):
        x, i = load(buf, i)
        items.append(x)
    return (dict(zip(items[::2], items[1::2])) if tag == b"d" else items), i


ada = {"name": "Ada", "born": 1815, "tags": ["math", "poet"]}
data = bytes(dump(ada, bytearray()))
print(len(data), "bytes:", data[:14])
print("round trip equal:", load(data)[0] == ada)

shared = ["x"]
back = load(bytes(dump([shared, shared], bytearray())))[0]
print("shared list after load: same object?", back[0] is back[1])
back = pickle.loads(pickle.dumps([shared, shared]))
print("with pickle: same object?", back[0] is back[1])

old = load(bytes(dump({"name": "Alan", "born": 1912}, bytearray())))[0]
print("old record, new reader:", old["name"], old.get("tags", []))
try:
    dump(lambda: 0, bytearray())
except TypeError as err:
    print("TypeError:", err)
Output
72 bytes: b'd\x00\x00\x00\x03s\x00\x00\x00\x04name'
round trip equal: True
shared list after load: same object? False
with pickle: same object? True
old record, new reader: Alan []
TypeError: cannot serialize function

The program defines a small binary format: a tag byte gives the type, a 4-byte length comes before each string, list and dictionary, and numbers take 8 bytes in big-endian order. A dictionary with three fields takes 72 bytes, and reading it gives an equal dictionary. A list that appears twice comes back as two separate lists, because the format writes values, not references; pickle writes a reference the second time and keeps one list. A record written before the tags field existed still loads, and the reader gives the missing field a default. A function cannot be written at all, because the format has no tag for code.

How it works

Formats. A text format, such as JSON, XML, CSV or YAML, writes values as characters that a person can read and that every language can parse. A binary format, such as Protocol Buffers, CBOR, MessagePack or a language's own format, writes numbers in a fixed number of bytes and is smaller and faster to read. A format is self-describing when the data carries the names of its fields, as JSON does, or schema-based when both sides share a definition of the fields, as Protocol Buffers does: "You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data".1

Mapping types to the format. Some code must walk each value and write its parts. There are three ways. Reflection reads the fields of a type when the program runs, as Go's encoding/json and Java's object streams do; Go uses the "json" key in "the struct field's tag" to give names and options.2 Code generation writes the serializer when the program compiles, as Rust's serde derive macros, the .NET source generator and the code from a .proto file do. Serde describes the design: "data structures that know how to serialize and deserialize themselves along with data formats that know how to serialize and deserialize other things".3 The third way, writing the code by hand, as the C, C++ and Rust example files do, gives full control of the bytes at the cost of more code to keep in step with the type.

What survives the trip. A serialized form holds data, not behavior: .NET says that "The serialized form doesn't include any information about an object's associated methods."4 Tree formats such as JSON write each value where it appears, so shared objects become copies, and a cycle is an error or an endless loop. Graph formats keep identity: Python's pickler remembers the objects it has seen, "so that shared or recursive objects are pickled by reference and not by value".5 JavaScript's structured clone keeps "a map of previously visited references, to avoid infinitely traversing cycles".6 Types can also change on the way. JSON has no dates, sets or tuples, and JSON.stringify drops values it cannot write: "undefined, Function, and Symbol values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to null (when found in an array)."7 Large integers lose precision in JavaScript, whose numbers are doubles.

Language formats and neutral formats. Several languages have a format of their own that can write almost any object: pickle in Python, object streams in Java, gob in Go and, formerly, BinaryFormatter in .NET. In Python, "“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation".5 In Java, "Serializability of a class is enabled by the class implementing the java.io.Serializable interface."8 Go's gob carries "binary values exchanged between an Encoder (transmitter) and a Decoder (receiver)".9 These formats are easy to use but tie the data to one language, and often to one version of the classes. Neutral formats such as JSON and Protocol Buffers work across languages; Protobuf calls itself "a language-neutral, platform-neutral extensible mechanism for serializing structured data".1

Versions. Data often outlives the program that wrote it, so a format must survive changes to the types. The usual rules are: a reader ignores fields it does not know, a missing field gets a default, a field is never reused with a new meaning, and a version number marks changes that break these rules. Protobuf follows them with numbered fields and supports "the addition of new fields and the deletion of existing fields, to any Protobuf message without breaking existing services".1 Java object streams compare a version number, the serialVersionUID, and if the reader's class "has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException".8 The Go, C# and Rust example files show both choices: ignore unknown fields, or reject them.

Security. A format that names the classes to create lets the bytes choose what code runs while they are read. The Python documentation warns: "The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling."5 Java's warning is "Deserialization of untrusted data is inherently dangerous and should be avoided."8 Microsoft ended the .NET format: "BinaryFormatter is insecure and can't be made secure."10 Read data from outside the program only with a data format such as JSON or Protobuf into types the program chooses, or with a filter that accepts only expected classes. See deserialization of untrusted data.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaStandard library
CIdiom
C#Standard library
JavaScriptNative
TypeScriptNativeTypeScript uses the JSON object of JavaScript, and the types are removed, so parsed data needs a check, but no example file exists.
GoStandard library
RustLibrary
KotlinLibraryThe kotlinx.serialization library and its compiler plugin generate serializers for classes marked with the Serializable annotation, but no example file exists because kotlinc is not installed.
SQLNativeThe JSON functions of SQL 2016, such as JSON_OBJECT and JSON_ARRAYAGG, turn rows into JSON text, and JSON_TABLE turns it back into rows.
BashIdiomDeclare -p prints a variable as shell code that recreates it, and jq handles JSON, but no example file exists.
PowerShellStandard libraryConvertTo-Json, ConvertFrom-Json, Export-Clixml and Import-Clixml serialize objects, but no example file exists because pwsh is not installed.
HTMLDoes not applyHTML is itself a serialization of a document tree, and it has no values to serialize.
CSSDoes not applyCSS has no values that a program serializes.
Regular expressionsDoes not applyRegular expressions match text and do not serialize values.
Language Verdict Mechanism
Python stdlib pickle, json, marshal; dataclasses through asdict
JavaScript native the JSON object; structuredClone on the web and in Node
TypeScript native as JavaScript; parsed values need a check
Java stdlib Serializable and object streams; Jackson for JSON
Kotlin library kotlinx.serialization with a compiler plugin
C# stdlib System.Text.Json with source generation
Go stdlib encoding/json with struct tags, encoding/gob
Rust library serde with derive macros, serde_json
C idiom fields written byte by byte; libraries
C++ idiom stream operators with std::quoted; libraries
Bash idiom declare -p; jq for JSON
PowerShell stdlib ConvertTo-Json, Export-Clixml
SQL native JSON functions; dumps of rows
Regex n/a no values to serialize
HTML n/a a serialization of a document tree
CSS n/a no values to serialize

JavaScript is native because the JSON object is part of the language, and SQL is native because the standard has JSON functions. Python, Java, C#, Go and PowerShell ship serialization in the standard library. Rust and Kotlin leave it to libraries, serde and kotlinx.serialization, which nearly every program uses and which generate code when the program compiles. C and C++ have no serialization, and programs write the bytes themselves or use a library.

The example files show the main tradeoffs. Python, Java and Go compare a language format, pickle, object streams or gob, with JSON, and show what each keeps. JavaScript shows what JSON loses and how structured clone keeps it. C# and Go show the choice between ignoring and rejecting unknown fields, and Java shows a filter that limits the classes that deserialization can create. Rust and C write binary formats by hand with a fixed byte order, and C++ writes a text format where quoting keeps strings with spaces intact.

PythonGitHub
import datetime
import json
import pickle
from dataclasses import asdict, dataclass, field


@dataclass
class Person:
    name: str
    born: int
    tags: list = field(default_factory=list)


ada = Person("Ada", 1815, ["math"])
back = pickle.loads(pickle.dumps(ada))  # binary, Python only
print(type(back).__name__, "equal:", back == ada, "same object:", back is ada)
loop = []
loop.append(loop)
again = pickle.loads(pickle.dumps(loop))
print("pickle keeps a cycle:", again[0] is again)

text = json.dumps(asdict(ada))  # text, any language
print(text)
print("from JSON:", Person(**json.loads(text)) == ada)
print("a tuple comes back as:", json.loads(json.dumps((1, 2))))
try:
    json.dumps(loop)
except ValueError as err:
    print("ValueError:", err)
try:
    json.dumps({"when": datetime.date(2026, 1, 1)})
except TypeError as err:
    print("TypeError:", err)
print(json.dumps({"when": datetime.date(2026, 1, 1)}, default=str))
Output
Person equal: True same object: False
pickle keeps a cycle: True
{"name": "Ada", "born": 1815, "tags": ["math"]}
from JSON: True
a tuple comes back as: [1, 2]
ValueError: Circular reference detected
TypeError: Object of type date is not JSON serializable
{"when": "2026-01-01"}
  • Verdict: stdlib. pickle writes any graph of Python objects to a binary format that only Python reads, and it keeps shared objects and cycles. json writes the common types to text that any language reads, and it loses what JSON cannot say: a tuple comes back as a list, a cycle is an error, and a date needs a default function. A dataclass goes through asdict on the way out and through its constructor on the way in. Never unpickle data from a source that is not trusted.
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

struct Person {
    std::string name;
    int born = 0;
    std::vector<std::string> tags;
    bool operator==(const Person&) const = default;
};

std::ostream& operator<<(std::ostream& os, const Person& p) {
    os << std::quoted(p.name) << ' ' << p.born << ' ' << p.tags.size();
    for (const auto& t : p.tags) os << ' ' << std::quoted(t);
    return os;
}

std::istream& operator>>(std::istream& is, Person& p) {
    std::size_t n = 0;
    is >> std::quoted(p.name) >> p.born >> n;
    p.tags.assign(n, "");
    for (auto& t : p.tags) is >> std::quoted(t);
    return is;
}

int main() {
    Person grace{"Grace \"Amazing\" Hopper", 1906, {"navy", "COBOL compilers"}};
    std::stringstream text;
    text << grace;
    std::cout << text.str() << '\n';
    Person back;
    text >> back;
    std::cout << "round trip: " << std::boolalpha << (back == grace) << '\n';

    std::stringstream raw; // no quoting: a space ends the field
    raw << grace.name << ' ' << grace.born;
    std::string name;
    int born = 0;
    raw >> name >> born;
    std::cout << "without quoting: name " << std::quoted(name) << ", born " << born
              << ", failed " << raw.fail() << '\n';
}
Output
"Grace \"Amazing\" Hopper" 1906 2 "navy" "COBOL compilers"
round trip: true
without quoting: name "Grace", born 0, failed true
  • Verdict: idiom. The standard library has streams but no serialization. The idiom defines operator<< and operator>> for each type, and std::quoted writes strings with quotes and escapes so that spaces and quotes survive. Without quoting, a space ends the name and the next read fails. Larger programs use libraries such as Boost.Serialization, cereal or Protocol Buffers.
JavaGitHub
import java.io.*;
import java.time.Instant;
import java.util.*;

public class Main {
    record Person(String name, int born, List<String> tags) implements Serializable {}

    static class Session implements Serializable {
        private static final long serialVersionUID = 1L;
        String user = "ada";
        transient String password = "secret"; // not written
    }

    static byte[] write(Object o) throws IOException {
        var bytes = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        return bytes.toByteArray();
    }

    static Object read(byte[] data) throws IOException, ClassNotFoundException {
        try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            // accept only the classes this program expects
            in.setObjectInputFilter(ObjectInputFilter.Config.createFilter(
                "Main$*;java.util.*;java.lang.*;!*"));
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        var ada = new Person("Ada", 1815, new ArrayList<>(List.of("math")));
        var back = (Person) read(write(ada));
        System.out.println(back + " equal: " + back.equals(ada));

        var session = (Session) read(write(new Session()));
        System.out.println("user " + session.user + ", password " + session.password);

        var shared = new ArrayList<>(List.of("x"));
        var pair = (List<?>) read(write(new ArrayList<>(List.of(shared, shared))));
        System.out.println("sharing kept: " + (pair.get(0) == pair.get(1)));

        try {
            write(new Object());
        } catch (NotSerializableException e) {
            System.out.println("NotSerializableException: " + e.getMessage());
        }
        try {
            read(write(Instant.EPOCH));
        } catch (InvalidClassException e) {
            System.out.println("filter rejected: " + e.getMessage());
        }
    }
}
Output
Person[name=Ada, born=1815, tags=[math]] equal: true
user ada, password null
sharing kept: true
NotSerializableException: java.lang.Object
filter rejected: filter status: REJECTED
  • Verdict: stdlib. A class that implements java.io.Serializable can go through ObjectOutputStream and ObjectInputStream, which keep shared references and skip transient fields. Records are serialized through their canonical constructor. The format names the classes to create, so reading untrusted bytes is dangerous; the example sets an ObjectInputFilter that accepts only the expected classes and rejects Instant. For data that other programs read, Java programs use JSON libraries such as Jackson.
#include <stdint.h>
#include <stdio.h>
#include <string.h>

struct reading {
    uint8_t sensor;
    uint32_t value;
    uint16_t flags;
};

/* Write each field byte by byte, little-endian, with no padding. */
static size_t encode(const struct reading *r, unsigned char *out) {
    out[0] = r->sensor;
    for (int i = 0; i < 4; i++) out[1 + i] = (unsigned char)(r->value >> (8 * i));
    for (int i = 0; i < 2; i++) out[5 + i] = (unsigned char)(r->flags >> (8 * i));
    return 7;
}

static struct reading decode(const unsigned char *in) {
    struct reading r = {0};
    r.sensor = in[0];
    for (int i = 0; i < 4; i++) r.value |= (uint32_t)in[1 + i] << (8 * i);
    for (int i = 0; i < 2; i++) r.flags |= (uint16_t)(in[5 + i] << (8 * i));
    return r;
}

int main(void) {
    struct reading r = {7, 1000000, 0x8001};
    unsigned char buf[16];
    size_t n = encode(&r, buf);
    printf("struct in memory: %zu bytes, encoded: %zu bytes\n", sizeof r, n);
    for (size_t i = 0; i < n; i++) printf("%02x%s", buf[i], i + 1 < n ? " " : "\n");
    struct reading back = decode(buf);
    printf("round trip: %d\n", back.sensor == r.sensor && back.value == r.value && back.flags == r.flags);
    return 0;
}
Output
struct in memory: 12 bytes, encoded: 7 bytes
07 40 42 0f 00 01 80
round trip: 1
  • Verdict: idiom. C has no serialization. Writing a struct with fwrite copies its padding and its byte order, which depend on the compiler and the machine; here the struct takes 12 bytes in memory and 7 in the encoded form. The idiom writes each field byte by byte in a fixed order, or uses a library such as Protocol Buffers for C.
using System.Text.Json;
using System.Text.Json.Serialization;

var ada = new Person("Ada", 1815, ["math"]);
string text = JsonSerializer.Serialize(ada, Ctx.Default.Person); // code made at compile time
Console.WriteLine(text);
var back = JsonSerializer.Deserialize(text, Ctx.Default.Person)!;
Console.WriteLine($"{back.Name} {back.Born} tags equal: {back.Tags.SequenceEqual(ada.Tags)}");

var web = new JsonSerializerOptions(JsonSerializerDefaults.Web) { TypeInfoResolver = Ctx.Default };
Console.WriteLine(JsonSerializer.Serialize(ada, web.GetTypeInfo(typeof(Person))));
Console.WriteLine(JsonSerializer.Serialize(new Login("ada", "secret"), Ctx.Default.Login));

const string newer = """{"Name":"Alan","Born":1912,"Died":1954}""";
var alan = JsonSerializer.Deserialize(newer, Ctx.Default.Person)!;
Console.WriteLine($"{alan.Name} {alan.Born}, Died ignored, Tags null: {alan.Tags is null}");
var strict = new JsonSerializerOptions
{
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
    TypeInfoResolver = Ctx.Default,
};
try
{
    JsonSerializer.Deserialize(newer, strict.GetTypeInfo(typeof(Person)));
}
catch (JsonException)
{
    Console.WriteLine("strict: JsonException for Died");
}

record Person(string Name, int Born, List<string> Tags);

record Login(string User, [property: JsonIgnore] string Password);

[JsonSerializable(typeof(Person))]
[JsonSerializable(typeof(Login))]
partial class Ctx : JsonSerializerContext;
Output
{"Name":"Ada","Born":1815,"Tags":["math"]}
Ada 1815 tags equal: True
{"name":"Ada","born":1815,"tags":["math"]}
{"User":"ada"}
Alan 1912, Died ignored, Tags null: True
strict: JsonException for Died
  • Verdict: stdlib. System.Text.Json is part of .NET. A JsonSerializerContext with [JsonSerializable] attributes makes the serialization code at compile time, which works with native AOT and starts faster than reflection. The web defaults change property names to camel case, [JsonIgnore] leaves a property out, and by default unknown properties are ignored and missing ones get default values; JsonUnmappedMemberHandling.Disallow makes unknown properties an error. BinaryFormatter throws on use since .NET 9, because it could not be made secure.
JavaScriptGitHub
const person = {
  name: "Ada",
  born: new Date(Date.UTC(1815, 11, 10)),
  tags: new Set(["math"]),
  note: undefined,
  greet() { return "hello"; },
};
const text = JSON.stringify(person);
console.log(text);
const back = JSON.parse(text);
console.log(typeof back.born, back.tags instanceof Set);
const revived = JSON.parse(text, (key, value) => (key === "born" ? new Date(value) : value));
console.log("revived year:", revived.born.getUTCFullYear());
try {
  JSON.stringify({ count: 10n });
} catch (err) {
  console.log("BigInt:", err.name);
}

const loop = { name: "loop" };
loop.self = loop;
const copy = structuredClone({ born: person.born, tags: person.tags, loop });
console.log(copy.born instanceof Date, copy.tags.has("math"), copy.loop.self === copy.loop);
try {
  structuredClone(person);
} catch (err) {
  console.log("function:", err.name);
}
Output
{"name":"Ada","born":"1815-12-10T00:00:00.000Z","tags":{}}
string false
revived year: 1815
BigInt: TypeError
true true true
function: DataCloneError
  • Verdict: native. The JSON object is part of the language. JSON.stringify drops undefined and functions, writes a Date as a string and a Set as an empty object, and throws a TypeError for a BigInt. A reviver function given to JSON.parse rebuilds the types. structuredClone, from the web platform and in Node, copies dates, sets, maps and cycles, but it throws a DataCloneError for a function.
package main

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"fmt"
	"strings"
)

type Person struct {
	Name  string   `json:"name"`
	Born  int      `json:"born"`
	Died  int      `json:"died,omitempty"`
	Tags  []string `json:"tags"`
	notes string   // not exported, so not serialized
}

func main() {
	ada := Person{Name: "Ada", Born: 1815, Tags: []string{"math"}, notes: "private"}
	data, _ := json.Marshal(ada)
	fmt.Println(string(data))
	var back Person
	_ = json.Unmarshal(data, &back)
	fmt.Printf("%s %d %v notes=%q\n", back.Name, back.Born, back.Tags, back.notes)

	newer := `{"name":"Alan","born":1912,"field":"logic"}`
	var alan Person
	err := json.Unmarshal([]byte(newer), &alan)
	fmt.Println(alan.Name, alan.Born, "tags nil:", alan.Tags == nil, "err:", err)
	dec := json.NewDecoder(strings.NewReader(newer))
	dec.DisallowUnknownFields()
	fmt.Println("strict:", dec.Decode(&Person{}))

	var buf bytes.Buffer // gob: a binary format for Go programs
	_ = gob.NewEncoder(&buf).Encode(ada)
	var g Person
	_ = gob.NewDecoder(&buf).Decode(&g)
	fmt.Printf("gob: %s %d %v\n", g.Name, g.Born, g.Tags)
	err = gob.NewEncoder(&buf).Encode(func() {})
	fmt.Println("gob func:", err != nil)
}
Output
{"name":"Ada","born":1815,"tags":["math"]}
Ada 1815 [math] notes=""
Alan 1912 tags nil: true err: <nil>
strict: json: unknown field "field"
gob: Ada 1815 [math]
gob func: true
  • Verdict: stdlib. encoding/json reads the exported fields of a struct through reflection, and struct tags give the JSON names and options such as omitempty. Fields that are not exported are skipped. Unknown fields are ignored, and missing ones keep their zero values, unless the decoder calls DisallowUnknownFields. encoding/gob is a binary format for Go programs that sends a description of each type with the data.
RustGitHub
#[derive(Debug, PartialEq)]
struct Person {
    name: String,
    born: i32,
    tags: Vec<String>,
}

const VERSION: u8 = 1;

fn put_str(out: &mut Vec<u8>, s: &str) {
    out.extend_from_slice(&(s.len() as u32).to_le_bytes()); // length prefix
    out.extend_from_slice(s.as_bytes());
}

struct Reader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
        if n > self.data.len() - self.pos {
            return Err(format!("needs {n} bytes at byte {}, has {}", self.pos, self.data.len() - self.pos));
        }
        self.pos += n;
        Ok(&self.data[self.pos - n..self.pos])
    }
    fn u32(&mut self) -> Result<u32, String> {
        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
    }
    fn string(&mut self) -> Result<String, String> {
        let n = self.u32()? as usize; // checked by take before any allocation
        String::from_utf8(self.take(n)?.to_vec()).map_err(|e| e.to_string())
    }
}

impl Person {
    fn encode(&self) -> Vec<u8> {
        let mut out = vec![VERSION];
        put_str(&mut out, &self.name);
        out.extend_from_slice(&self.born.to_le_bytes());
        out.extend_from_slice(&(self.tags.len() as u32).to_le_bytes());
        for t in &self.tags {
            put_str(&mut out, t);
        }
        out
    }

    fn decode(data: &[u8]) -> Result<Person, String> {
        let mut r = Reader { data, pos: 0 };
        match r.take(1)?[0] {
            VERSION => {}
            v => return Err(format!("unknown version {v}")),
        }
        let name = r.string()?;
        let born = i32::from_le_bytes(r.take(4)?.try_into().unwrap());
        let count = r.u32()?;
        let tags = (0..count).map(|_| r.string()).collect::<Result<_, _>>()?;
        Ok(Person { name, born, tags })
    }
}

fn main() {
    let ada = Person { name: "Ada".into(), born: 1815, tags: vec!["math".into()] };
    let bytes = ada.encode();
    println!("{} bytes: {:?}", bytes.len(), &bytes[..12]);
    println!("round trip: {}", Person::decode(&bytes) == Ok(ada));
    println!("cut short: {:?}", Person::decode(&bytes[..10]));
    let mut newer = bytes.clone();
    newer[0] = 2;
    println!("newer file: {:?}", Person::decode(&newer));
    let evil = [1, 0xff, 0xff, 0xff, 0xff, b'A'];
    println!("huge length: {:?}", Person::decode(&evil));
}
Output
24 bytes: [1, 3, 0, 0, 0, 65, 100, 97, 23, 7, 0, 0]
round trip: true
cut short: Err("needs 4 bytes at byte 8, has 2")
newer file: Err("unknown version 2")
huge length: Err("needs 4294967295 bytes at byte 5, has 1")
  • Verdict: library. The standard library has no serialization framework; the serde crate is the common choice, with #[derive(Serialize, Deserialize)] and a separate crate for each format, such as serde_json. The example writes a binary format by hand with a version byte and length prefixes, and the decoder returns an error, not a panic, for short input, an unknown version or a length larger than the input.
  • Schema languages. Protocol Buffers, Thrift, Avro, Cap'n Proto and FlatBuffers define messages in a schema and generate code for each language. Cap'n Proto and FlatBuffers use a layout that a program can read without a separate decoding step.
  • Binary JSON. CBOR, MessagePack and BSON keep the data model of JSON and write it in binary.
  • Text formats. JSON, XML, YAML, TOML and CSV are text formats; see read and write JSON for the common task.
  • Deep copy. Serializing and reading back is a slow way to make a deep copy, and structured clone does the same in one step.
  • Remote calls. RPC systems such as gRPC serialize the arguments and results of calls across a network.
  • Persistence. Object databases and ORMs map objects to stored data, a form of serialization with queries.
  • Canonical forms. Signatures and hashes need one exact byte sequence for each value, so formats such as canonical CBOR and the JSON Canonicalization Scheme fix the order of keys and the form of numbers. The built-in hash codes are not stable enough for this.

Pitfalls

  • Deserializing untrusted data with a language format. Pickle, Java object streams and BinaryFormatter can run code chosen by the sender. Use a data format, or a filter of allowed classes.
  • Writing memory as it is. Writing a C struct or a Rust value as raw bytes copies padding, pointers and the byte order of the machine. Write each field in a defined order and size.
  • Lost types. A date becomes a string, a set an empty object, a tuple a list, and a 64-bit integer a double in JavaScript. Convert these types on both sides, or choose a format that has them.
  • Shared references and cycles. Tree formats copy shared objects and fail on cycles. Use IDs in the data, or a graph format.
  • Silent changes to the schema. Renaming a field, changing its type or reusing a field number breaks old data with no error. Keep old names, add fields with defaults, and test reading data from older versions.
  • Trusting lengths and counts. A length prefix of four billion should give an error, not an attempt to allocate four billion bytes; the Rust file checks lengths against the remaining input. Limit the size of the input and the depth of nesting.
  • Floating-point text. Writing a float with too few digits changes its value on the way back. Most JSON libraries write the shortest form that reads back as the same value; others need care.

Cost

Serialization reads every part of a value, so its time grows with the size of the data. Reflection costs a lookup of the type's fields at run time, usually cached after the first call; generated code avoids it, which is why .NET's source generator and serde are fast. Text formats cost more than binary ones, both to write and to parse, and they are often two to ten times larger before compression. Formats with names in each record, such as JSON, repeat the names; schema formats such as Protobuf write small field numbers. Formats that need no decoding step, such as FlatBuffers, read a field in constant time, at the cost of a larger and more fixed layout.

History

Network protocols needed formats that every machine could read. Xerox's Courier defined one in the early 1980s, ASN.1 became a standard in 1984, and Sun published XDR, with a fixed byte order and alignment, for its remote procedure calls in 1987. Distributed objects in CORBA and Java RMI needed to send objects, and Java 1.1 added object serialization in 1997.8 XML, from 1998, became the text format of web services, and Douglas Crockford described JSON in 2001 as a simpler subset of JavaScript.

Google built Protocol Buffers for its internal services and released it as open source in 2008.1 Facebook released Thrift in 2007, and Avro, MessagePack, Cap'n Proto and FlatBuffers followed. Attacks with Java gadget chains in 2015 showed the danger of formats that create any class, and Java added deserialization filters in 2017. Erick Tryzelaar started serde for Rust in 2014, and David Tolnay later became its main author. .NET Core 3.0 added System.Text.Json in 2019,4 and .NET 9 disabled BinaryFormatter in 2024.10

References

  1. Overview, Protocol Buffers documentation, Overview and Open Source Philosophy
  2. Package json, Go standard library documentation, func Marshal
  3. Overview, Serde, Overview
  4. JSON serialization and deserialization in .NET, overview, Overview
  5. pickle, Python object serialization, Python documentation, Introduction and Pickler
  6. The structured clone algorithm, MDN Web Docs, Description and things that do not work
  7. JSON.stringify(), MDN Web Docs, Description
  8. Interface Serializable, Java SE 25 API documentation, Interface description
  9. Package gob, Go standard library documentation, Overview
  10. Deserialization risks in use of BinaryFormatter and related types, .NET documentation, Caution and note

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/TNYDZ9/text.yaml