Java JSON Processing with Jackson: Bean Mapping, Collections & Tree Model
This tutorial demonstrates how to use Jackson in Java for JSON processing, covering Maven dependency setup, JavaBean serialization, collection mapping with TypeReference for generics, and tree-model parsing via JsonNode to extract fields without POJOs.
Introduction to JSON and Jackson
JSON (JavaScript Object Notation) is a lightweight, language-independent data interchange format that is easy for humans to read and write and for machines to parse and generate. This article explains how to use the Jackson library in Java to convert between Java objects and JSON strings, and how to parse JSON without predefined JavaBeans using the tree model.
Maven Project Setup
Create a Maven project and add the jackson-databind dependency (version 2.13.1). Because jackson-databind transitively depends on jackson-core (streaming API) and jackson-annotations (annotation package), only one dependency is required. Also add JUnit 4.13.2 for testing.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>After refreshing Maven, the required JARs are downloaded automatically.
Project Structure
com.jobs.bean.employee– Employee entity class with name (String) and age (Integer), including overridden equals, hashCode, and toString methods. test/com.jobs.jsonTest – JUnit test class containing four test methods. resources/data.json – Sample JSON file used for parsing demonstrations.
Sample JSON Data
{
"status": 0,
"msg": "成功",
"data": {
"address": {
"street": "黄金屋",
"city": "科技复兴",
"province": "地球"
},
"friends": ["侯胖胖", "任肥肥", "蔺赞赞", "李敦敦", "杨帅帅"]
}
}Core Conversion Examples
1. JavaBean ↔ JSON (test01)
Use ObjectMapper.writeValueAsString() to serialize an employee instance to JSON, and readValue(json, Employee.class) to deserialize back.
employee emp = new employee("侯胖胖", 40);
String json = mapper.writeValueAsString(emp);
// Output: {"name":"侯胖胖","age":40}
employee result = mapper.readValue(json, employee.class);2. Java Collections with Primitive Types ↔ JSON (test02)
Demonstrates List<String>, Map<String, Integer>, and Set<String> serialization and deserialization. Note that deserializing to generic collections requires only the raw class (e.g., List.class), which yields raw types; type safety is not enforced at runtime.
List<String> list = new ArrayList<>();
list.add("候胖胖");
String listJson = mapper.writeValueAsString(list);
List<String> listResult = mapper.readValue(listJson, List.class);3. Java Collections with Custom JavaBeans ↔ JSON (test03)
When collections contain custom objects (e.g., List<employee>), Jackson cannot infer the generic type at runtime due to type erasure. The solution is to use TypeReference:
List<employee> listResult = mapper.readValue(listJson,
new TypeReference<List<employee>>() {});The same pattern applies to Map<String, employee> and Set<employee>. The article shows that duplicate employee objects (same name and age) are correctly deduplicated in the Set because equals and hashCode are overridden.
4. Parsing JSON Without JavaBeans Using JsonNode Tree Model (test04)
When you don't want to create a POJO for every JSON structure, you can parse the JSON into a JsonNode tree and navigate it. The example reads data.json from the classpath, loads it into a String, and then:
Extracts status as int via root.get("status").asInt().
Extracts msg as String via root.get("msg").asText().
Navigates to nested address object and reads street, city, province.
Iterates over the friends array using a for-each loop on JsonNode items.
JsonNode root = mapper.readTree(json);
int status = root.get("status").asInt();
String msg = root.get("msg").asText();
JsonNode address = root.get("data").get("address");
String street = address.get("street").asText();
// ...
JsonNode friends = root.get("data").get("friends");
for (JsonNode item : friends) {
System.out.println(item.asText());
}This approach is useful for ad-hoc JSON parsing when the schema is dynamic or only a subset of fields is needed.
Key Takeaways
Add only jackson-databind to get all three Jackson modules.
Use ObjectMapper as the central class for all conversions.
For generic collections of custom types, always use TypeReference to preserve type information.
The tree model ( JsonNode) enables schema-less JSON navigation without POJOs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
