Java
List and Map serialization
Learn to convert List and Map structures to JSON.
Serializing a list
To convert a List<User> to structured text, you still use writeValueAsString. The output is a text array: [{"name":"Ayşe","age":30},{"name":"Mehmet","age":25}].
Because of type erasure, readValue on collections needs an extra TypeReference: mapper.readValue(text, new TypeReference<List<User>>(){}). This anonymous class carries the generic type at runtime.
Serializing a Map
A Map<String, Integer> becomes a structured text object: keys become text keys, values become text values. A Map<String, User> produces nested objects. Reading also uses TypeReference<Map<String, User>>().
Jackson needs no separate code for List and Map; the same writeValueAsString and readValue methods work. Type safety comes from TypeReference.
Exercise Convert a User list to structured text
Define record User(String name, int age) {}. Add throws Exception to main. Create an ObjectMapper mapper = new ObjectMapper();, build a List<User> users = new ArrayList<>();, add users.add(new User("Ayşe", 30)); and users.add(new User("Mehmet", 25));. Produce text with String text = mapper.writeValueAsString(users); and print System.out.println(text);.
Show example solution
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.ArrayList;
record User(String name, int age) {}
public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
List<User> users = new ArrayList<>();
users.add(new User("Ayşe", 30));
users.add(new User("Mehmet", 25));
String text = mapper.writeValueAsString(users);
System.out.println(text);
}
}
Test yourself
-
Complete the list type reference
mapper.readValue(text, new ____<List<User>>() {});
Show answer
mapper.readValue(text, new TypeReference<List<User>>() {});
-
What happens when List<User> is converted to structured text?
- A text object
- A text array
- It throws an error
- An empty string
Show answer
A text array — A List becomes a text array ([...]).
-
Match the collection serialization concepts
- List<User>
- Becomes a text array
- Map<String, User>
- Becomes a text object
- TypeReference
- Generic type info
- writeValueAsString
- Common serialization method
Next lesson: Summary - Serialization