liveBook · Manning

Serialization

As explained in Clojure: The Essential Reference

Serialization is the conversion of structured data or objects into a linear representation that can be persisted or transmitted and later reconstructed.

Serialization converts nested data structures or objects into a linear representation that can be written to disk or sent over a network, then reconstructed. In Clojure, pr-family functions produce representations that read-string can read back, while print-family functions target human-readable output. section 18.2

Choose the representation and output path according to the task:

  • Use pr-str or prn-str when a string representation should remain readable by Clojure; use print-str or println-str for human-oriented text. section 18.2
  • Bind *out* to a Writer or OutputStream to redirect output, including large lazy sequences, directly to a file. section 18.2
  • Extend print-method for readable custom types, and use print-dup with print-ctor when reconstructible forms are required. section 18.4
  • Treat print-dup and read-string as unsafe for uncontrolled data because evaluated representations permit code injection; prefer EDN when appropriate. section 18.4

Readable and reconstructible custom data

A Point type can print as "[x=1, y=2]" for ordinary display, while print-dup can emit "#=(user.Point. 1 2)". Reading and evaluating the latter reconstructs a Point instance, but only trusted serialized data should be evaluated. section 18.4

(pr "a" 'a \a) ; #1
;; "a" a \a
;; nil

(print "a" 'a \a) ; #2
;; a a a
;; nil

Compare pr's reader-friendly quoting with print's human-oriented output for the same values. section 18.2

How Clojure: The Essential Reference covers it

How deep it goes
Explains representations, output routing, custom printing, reconstruction, and code-injection risk without surveying binary formats.
Examples
Uses Clojure maps, sequences, Java maps, files, lazy ranges, and a custom Point type.
What it assumes
Assumes familiarity with Clojure data structures and introduces serialization through printing, reading, evaluation, and Java objects.
What you can do after
Build it from scratch by choosing printing functions, redirecting output, and extending custom-type serialization.
How it connects
Connects Clojure printing with read-string, print-method, print-dup, print-ctor, EDN, lazy sequences, and distributed systems.

Also explained in

Compare how 24 books explain serialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.