CodeGym /Courses /JAVA 25 SELF /Standard serialization formats: binary, text

Standard serialization formats: binary, text

JAVA 25 SELF
Level 42 , Lesson 2
Available

1. Binary serialization in Java

Binary serialization is Java’s standard mechanism by which an object is turned into a stream of bytes as compactly and quickly as possible. It uses the ObjectOutputStream and ObjectInputStream classes. The resulting file is a set of bytes that is not meant to be human-readable.

It’s called binary because everything is serialized in a “raw” form: numbers, strings, arrays, even references between objects are turned into bytes. It’s like a tightly packed suitcase: efficient and fast, but without instructions it’s not obvious where anything is.

How does it work in Java?

Suppose we have a User class:

import java.io.Serializable;

public class User implements Serializable {
    private String name;
    private int age;

    // Constructor, getters and setters
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}

Serialization to a binary file

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

User user = new User("John", 30);

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.bin"))) {
    out.writeObject(user);
    System.out.println("User object serialized to the file user.bin");
} catch (Exception e) {
    e.printStackTrace();
}

Deserialization from a binary file

import java.io.FileInputStream;
import java.io.ObjectInputStream;

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.bin"))) {
    User loadedUser = (User) in.readObject();
    System.out.println("Read from file: " + loadedUser.getName() + ", " + loadedUser.getAge());
} catch (Exception e) {
    e.printStackTrace();
}

Note: if you open the user.bin file in a text editor, you’ll see something like: ¬í sr ... — that’s normal; it’s by design!

Advantages of binary serialization

  • Compactness and speed. Saving and reading are as fast as possible, without extra “bells and whistles”.
  • All fields of the object are preserved, including nested objects (as long as they are also serializable via Serializable).
  • Simple to use for internal caching or transferring between Java programs.

Disadvantages

  • Not human-readable. You cannot “peek” into the contents and understand what’s inside.
  • Tight coupling to the class version. Changing the structure (adding/removing fields) can “break” reading old files.
  • Compatibility issues across different versions of Java and the JVM.
  • Not suitable for interoperability with other programming languages.
  • Security: deserializing data from untrusted sources is a direct path to vulnerabilities.

2. Text serialization formats: JSON, XML, and others

Binary serialization is good for internal use, but often you need to exchange data across different languages (Java, JavaScript, Python) or store it in a readable form — convenient for configurations, logs, and APIs. For this, text formats are used: JSON, XML, YAML, CSV, etc.

JSON — the most popular

JSON (JavaScript Object Notation) is a compact and readable format. An example of a serialized User object:

{
  "name": "John",
  "age": 30
}

In Java, the most commonly used libraries for JSON are: Jackson (the most popular), Gson, as well as Moshi, JSON-B, etc.

XML — a programmer’s old friend

XML (Extensible Markup Language) is more ‘verbose’, but formal and strict.

<User>
  <name>John</name>
  <age>30</age>
</User>

For XML in Java, the standard JAXB library is often used (or the older XStream).

YAML, CSV, and others

  • YAML — similar to JSON but more concise; more often used for configs than for serializing complex objects.
  • CSV — good for “flat” tables, but not well-suited for nested structures.
  • There are many other formats, but in Java the most common are JSON and XML.

3. Comparing formats: when to use what?

Format Readability Compactness Speed Compatibility When to use
Binary No ++ ++ Java only Internal cache, fast saving between JVMs
JSON Yes + + Any languages REST APIs, integration with external services, configs
XML Yes - - Any languages Integration, strict schemas, legacy systems
  • Binary — choose it for internal use when you don’t need to exchange data with external systems and maximum performance matters.
  • JSON — the best choice for exchanging data with web applications, mobile clients, and REST APIs, as well as for storing settings.
  • XML — needed for strict schemas and integration with “enterprise” solutions.

Important! Binary serialization is suitable only for transferring data between Java programs, and even then it’s safer to use it between programs of the same version. Text formats such as JSON and XML are more universal: they are suitable for data exchange across different languages and platforms, making information readable and portable.

4. Practice: serializing to binary and text formats

Binary serialization (ObjectOutputStream/ObjectInputStream)

We saw this above, but let’s repeat to reinforce:

// Serialization
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.bin"))) {
    out.writeObject(user);
}

// Deserialization
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.bin"))) {
    User loadedUser = (User) in.readObject();
}

Serializing to JSON with Jackson (briefly)

To work with Jackson, you need to add its libraries to the project. We’ll study Maven and Gradle later; for now, you can add the JAR files manually. Example dependency for Maven:

<!-- Maven -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
</dependency>

Example of serialization/deserialization:

import com.fasterxml.jackson.databind.ObjectMapper;

User user = new User("John", 30);
ObjectMapper mapper = new ObjectMapper();

try {
    // Serialization to a string
    String json = mapper.writeValueAsString(user);
    System.out.println(json); // {"name":"John","age":30}

    // Serialization to a file
    mapper.writeValue(new File("user.json"), user);

    // Deserialization from a string
    User loadedUser = mapper.readValue(json, User.class);

    // Deserialization from a file
    User loadedFromFile = mapper.readValue(new File("user.json"), User.class);

} catch (Exception e) {
    e.printStackTrace();
}

A JSON file can be opened in any text editor, which makes the data easy to read and portable across different applications and languages.

5. Which format to use: practical tips

  • Internal caching, temporary files, fast write/read between Java programs: use standard binary serialization. But remember version compatibility!
  • Integrating with external services, storing settings, front-end integration: use JSON (Jackson, Gson).
  • Integration with “enterprise” systems that require a strict schema: XML (JAXB).
  • You need a human to be able to open and read the file: JSON or XML, but not a binary format.

6. Common mistakes when working with serialization formats

Mistake No. 1: Trying to serialize an object with non-serializable fields. If your class has a field that does not implement Serializable (for example, a stream or a DB connection), binary serialization will throw an error. For JSON this is less critical, but there can also be issues with “nonstandard” types.

Mistake No. 2: Opening a binary file in a text editor and getting scared. That’s normal! Binary files are not intended for human reading.

Mistake No. 3: Changing the class structure and old binary files stop being readable. Binary serialization is sensitive to changes in class structure — InvalidClassException occurs frequently. In JSON/XML this is less critical: unknown fields are usually ignored or assigned default values.

Mistake No. 4: Using binary serialization for integration with external systems. This won’t work: the binary format is understood only by Java, and even then only when versions match.

Mistake No. 5: Forgetting to add the required annotations for JSON/XML. Some libraries require annotations such as @JsonProperty, @XmlElement; otherwise serialization/deserialization may not behave as expected.

Mistake No. 6: Not checking that all nested objects are serializable. For binary serialization this is a common problem; for JSON as well, if your model includes complex types.

1
Task
JAVA 25 SELF, level 42, lesson 2
Locked
Serialize an object to a binary file
Serialize an object to a binary file
1
Task
JAVA 25 SELF, level 42, lesson 2
Locked
Deserialization of an object from a binary file
Deserialization of an object from a binary file
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION