Java
readValue
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.
Exercise 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());.
Show example 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());
}
}
Test yourself
-
Complete the readValue call
User u = mapper.____(text, User.class);
Show answer
User u = mapper.readValue(text, User.class);
-
When does readValue throw IOException?
- Only on network errors
- Only when the file is missing
- On invalid text or type mismatch
- Never
Show answer
On invalid text or type mismatch — Invalid text or incompatible types throw IOException.
-
Match the readValue concepts
- readValue
- Text to object
- User.class
- Target type
- IOException
- Checked exception
- text String
- First parameter
Next lesson: writeValueAsString