CodeBlanks Logo Icon CodeBlanks

Summary - Serialization

Combine ObjectMapper and @JsonProperty to write a config file.

Summary - Serialization

In this group you learned structured text serialization with Jackson. ObjectMapper is the central class; writeValueAsString goes from object to text, readValue from text to object. With @JsonProperty you set key names; with the null-skipping annotation you controlled empty fields. TypeReference was used for List and Map.

This summary will serialize a User record and read it back.

Practice Serialize and read back a User

Define record User(String name, int age) {}. Add throws Exception to main. Create an ObjectMapper mapper = new ObjectMapper();, build a user with User u = new User("Ayşe", 30);, serialize with String text = mapper.writeValueAsString(u);, read back with User u2 = mapper.readValue(text, User.class); and print System.out.println(u2.name() + " " + u2.age());.

Starter code

Main.java
import com.fasterxml.jackson.databind.ObjectMapper;

// Define the User record

public class Main {
    public static void main(String[] args) throws Exception {
        // ObjectMapper, User instance, writeValueAsString, readValue and println

    }
}

Sample solution

Main.java
import com.fasterxml.jackson.databind.ObjectMapper;

record User(String name, int age) {}

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        User u = new User("Ayşe", 30);
        String text = mapper.writeValueAsString(u);
        User u2 = mapper.readValue(text, User.class);
        System.out.println(u2.name() + " " + u2.age());
    }
}

Expected output

Ayşe 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method converts text to an object?

  • getProperty
  • writeValueAsString
  • readValue Correct answer
  • toText

Explanation: readValue converts structured text into a Java object.

2 Annotation that customizes the key

Question
@____("user_name") String userName
Answer
@JsonProperty("user_name") String userName

Explanation: @JsonProperty sets the text key.

3 Match the serialization summary

Term Meaning
ObjectMapper Central converter
writeValueAsString Object to text
readValue Text to object
@JsonProperty Text key name

All lessons in Intermediate