readValue
- Java course
- Intermediate
- Lesson 77/116
- 5 min
Learn to build objects from JSON with readValue.
readValue from text to object
The mapper.readValue(text, User.class) call converts structured text into a Java object. The first parameter is the text (String or Reader); the second is the target class. Keys must match field names; otherwise use @JsonProperty.
readValue throws a checked IOException; the call requires try/catch or throws. The returned object is a User instance; fields are accessed via the record accessor methods.
Handling IOException
Invalid text or incompatible types throw IOException. It is a checked exception; the compiler forces handling: try { ... } catch (IOException e) { ... } or add throws IOException to the method signature.
The error message usually says where the problem is: unexpected token, missing field, type mismatch. Printing it during development helps you locate the issue quickly.
Practice Use readValue to build a User from text
Define record User(String name, int age) {}. Add throws Exception to main. Create an ObjectMapper mapper = new ObjectMapper();, define String text = "{\"name\":\"Ayşe\",\"age\":30}";, parse with User u = mapper.readValue(text, User.class);, and print System.out.println(u.name() + " " + u.age());.
Starter code
import com.fasterxml.jackson.databind.ObjectMapper;
// Define the User record
public class Main {
public static void main(String[] args) throws Exception {
// ObjectMapper, text, readValue and println
}
}Sample solution
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();
String text = "{\"name\":\"Ayşe\",\"age\":30}";
User u = mapper.readValue(text, User.class);
System.out.println(u.name() + " " + u.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 Complete the readValue call
User u = mapper.____(text, User.class);
User u = mapper.readValue(text, User.class);
Explanation: readValue converts text into a User object.
2 When does readValue throw IOException?
- Only on network errors
- Only when the file is missing
- On invalid text or type mismatch Correct answer
- Never
Explanation: Invalid text or incompatible types throw IOException.
3 Match the readValue concepts
| Term | Meaning |
|---|---|
readValue |
Text to object |
User.class |
Target type |
IOException |
Checked exception |
text String |
First parameter |