Advanced level · Module 4: HTTP Clients and JSON in Java · Lesson 3 of 4
JSON with Jackson
Convert JSON to Java records and back with Jackson, and handle nested data, lists and unknown fields.
In this lesson you will
- Deserialize JSON into records and lists with ObjectMapper
- Serialize Java objects to JSON and configure unknown-field handling
Key concepts
JSON object and arrayObjectMapperreadValue / writeValueAsStringTypeReference
The lesson
JSON represents data as objects in braces, arrays in square brackets, and strings, numbers, booleans and null. Jackson's ObjectMapper converts JSON text to Java objects and back; records work well as targets because their fields match the JSON keys.
mapper.readValue(json, Rate.class) reads one object. For a list, use new TypeReference<List<Rate>>() {} because generic types are erased at run time. writeValueAsString(object) produces JSON.
APIs often add fields over time. Configure the mapper to ignore unknown properties so your client does not break when a new field appears, and validate the fields you depend on.
Step by step
- Add the Jackson databind dependency.
- Define a record matching a sample JSON object.
- Read a JSON array into a List of records.
- Write a record back to JSON and print it.
Practice activity
Parse a provided JSON file of clinic appointments into records, calculate appointments per doctor and write the summary as JSON.
Expected result: The summary JSON has the correct counts and is valid when checked with a JSON validator.
Check your understanding
-
Why is TypeReference needed to read a List<Rate>?
Show answer
Generic type information is erased at run time, so Jackson needs it supplied explicitly.
-
Why ignore unknown JSON properties?
Show answer
So the client keeps working when the API adds new fields.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.