Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Serialization

Basic Usage

Every Serde(format, T) instance exposes a serialize method:

const json = serde.Serde(.json, MyStruct);

var buf: [1024]u8 = undefined;
var writer = std.Io.Writer.fixed(&buf);
try json.serialize(&writer, my_value);
const output = writer.buffered(); // the serialized bytes

The writer is a std.Io.Writer, which is the standard Zig I/O interface. You can use fixed buffers, buffered writers, or any other writer implementation.

Struct Serialization

Struct fields are serialized in declaration order:

const Point = struct {
    x: i32,
    y: i32,
};

// JSON: {"x":1,"y":2}
// TOML: x = 1\ny = 2
// YAML: x: 1\ny: 2

Optional Fields

Optional fields with null values are included by default:

const Data = struct {
    name: []const u8,
    note: ?[]const u8 = null,
};

// JSON: {"name":"alice","note":null}

Use omit_null to suppress null values from output. See Field Options.

Enum Serialization

Enums are serialized as their tag name string:

const Color = enum { red, green, blue };
// "red", "green", "blue"

Nested Types

Structs, arrays, and slices can be nested arbitrarily:

const Config = struct {
    name: []const u8,
    tags: []const []const u8,
    metadata: struct {
        version: u32,
        debug: bool,
    },
};