List and Map serialization
- Java course
- Intermediate
- Lesson 80/116
- 5 min
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.
Practice 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);.
Starter code
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.ArrayList;
// Define the User record
public class Main {
public static void main(String[] args) throws Exception {
// ObjectMapper, users list, two User adds, writeValueAsString and println
}
}Sample 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);
}
}Expected output
[{"name":"Ayşe","age":30},{"name":"Mehmet","age":25}]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the list type reference
mapper.readValue(text, new ____<List<User>>() {});
mapper.readValue(text, new TypeReference<List<User>>() {});
Explanation: TypeReference carries the generic type.
2 What happens when List<User> is converted to structured text?
- A text object
- A text array Correct answer
- It throws an error
- An empty string
Explanation: A List becomes a text array ([...]).
3 Match the collection serialization concepts
| Term | Meaning |
|---|---|
List<User> |
Becomes a text array |
Map<String, User> |
Becomes a text object |
TypeReference |
Generic type info |
writeValueAsString |
Common serialization method |