?? JSON Handling in Java with Jackson

?? JSON Handling in Java with Jackson

Here we will help you to understand JSON processing in Java, including parsing, serialization, deserialization, and converting data between formats (e.g. JSON ? XML). The focus is on Real World use cases with Jackson, one of the most widely used JSON libraries in Java.


?? 1. What is JSON and Why is it Used?

? JSON (JavaScript Object Notation) is a lightweight data format used for data exchange between systems.

? It is human-readable, easy to parse, and widely used in REST APIs.

? Java Application often consume or produce JSON when interacting with APIs, databases or message queues.

?? Example of JSON Data:

{
 "id": 1000,
  "name": "Marcelo Santos.",
  "email": "[email protected]",
  "roles": ["USER", "ADMIN"]
}        

??? 2. Working with JSON in Java

? How to convert JSON to Java Objects (Deserialization)?

?? Example: Converting JSON to Java Object using Jackson

import com.fasterxml.jackson.databind.ObjectMapper;
class User {
    public int id;
    public String name;
    public String email;
    public String[] roles;
}
public class JsonToJava {
    public static void main(String[] args) throws Exception {
        String json = "{\"id\":1000, \"name\":\"Marcelo Santos\", \"email\":\"[email protected]\", \"roles\":[\"USER\", \"ADMIN\"]}";
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(json, User.class);
        System.out.println("User Name: " + user.name);
    }
}        

? Output:

User Name: Marcelo Santos        

?? Use Case: Converting API responses to Java objects for further processing.

? How to Convert Java Objects to JSON (Serialization)

?? Example: Converting Java Object to JSON using Jackson

import com.fasterxml.jackson.databind.ObjectMapper;
class Product {
    public int id;
    public String name;
    public double price;
    public Product(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
}
public class JavaToJson {
    public static void main(String[] args) throws Exception {
        Product product = new Product(1, "Laptop", 2500.99);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(product);
        System.out.println(jsonString);
    }
}        

? Output:

{"id":1,"name":"Laptop","price": 2500.99}        

?? Use Case: Sending JSON responses in REST APIs.


?? 3. Customizing JSON with Jackson

? Ignoring Fields in JSON Serialization

?? Example: Using @JsonIgnore to Hide Fields

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
class Employee {
    public String name;
    
    @JsonIgnore
    public String ssn;  // This field will not be serialized
    public Employee(String name, String ssn) {
        this.name = name;
        this.ssn = ssn;
    }
}
public class IgnoreFieldExample {
    public static void main(String[] args) throws Exception {
        Employee employee = new Employee("Marcelo Santos", "123-456-789");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}        

? Output:

{"name":"Marcelo Santos"}        

?? Use Case: Hiding sensitive fields (e.g., passwords, SSNs) in API responses.

? Changing JSON Property Names

?? Example: Using @JsonProperty to Rename Fields

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
class Customer {
    @JsonProperty("full_name")
    public String name;
    public Customer(String name) {
        this.name = name;
    }
}
public class RenameJsonField {
    public static void main(String[] args) throws Exception {
        Customer customer = new Customer("Marcelo Santos");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(customer);
        System.out.println(jsonString);
    }
}        

? Output:

{"full_name":"Marcelo Santos"}        

?? Use Case: Adapting Java fields to match API contract requirements.


?? 4. Converting JSON ? XML in Java

?? Example: Using Jackson for JSON → XML Conversion

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class JsonToXml {
    public static void main(String[] args) throws Exception {
        String json = "{\"id\":1000, \"name\":\"Marcelo Santos", \"email\":\"[email protected]\"}";
        ObjectMapper jsonMapper = new ObjectMapper();
        XmlMapper xmlMapper = new XmlMapper();
        Object obj = jsonMapper.readValue(json, Object.class);
        String xml = xmlMapper.writeValueAsString(obj);
        System.out.println(xml);
    }
}        

? Output:


<Object>
  <id>1000</id>
  <name>Marcelo Santos</name>
  <email>[email protected]</email>
</Object>        

?? Use Case: Converting JSON responses into XML format for legacy systems.

?? Example: Convert XML → JSON

public class XmlToJson {
    public static void main(String[] args) throws Exception {
        String xml = "<Object><id>1000</id><name>Marcelo Santos</name><email>[email protected]</email></Object>";
        XmlMapper xmlMapper = new XmlMapper();
        ObjectMapper jsonMapper = new ObjectMapper();
        Object obj = xmlMapper.readValue(xml, Object.class);
        String json = jsonMapper.writeValueAsString(obj);
        System.out.println(json);
    }
}        

? Output:

{"id":1000,"name":"Marcelo Santos","email":"[email protected]"}        

?? Use Case: Integrating modern JSON-based APIs with legacy XML-based systems.


?? 5. Jackson Core use

? ObjectMapper, used for converting Java objects to/from JSON, providing powerful features to serialize Java objects into JSON and deserialize JSON into Java Objects. Remember, JSON to/from Java, use ObjectMapper.

JSON to Java is Deserialization

Java to JSON is Serialization

? XmlMapper (Extends ObjectMapper), is responsible for handling XML serialization and deserialization, working similarly to ObjectMapper, but instead JSON it process XML.

??Key Methods in ObjectMapper and XmlMapper

? readValue(String content, Class<T> valueType), converts JSON (or XML in XMLMapper) into a JavaObject, used to deserialization

? writeValue(File resultFile, Object value), used to write Java Object as JSON or XML into a file.

? writeValueAsString(Object value), used to converts Java Objects into JSON or XML Strings

??Most Commonly Used Jackson Annotations

1?? @JsonProperty, renames a field in JSON

2?? @JsonIgnore, excludes a field from serialization

3?? @JsonInclude(JsonInclude.Include.NON_NULL), excludes null values from JSON output

4?? @JsonFormat(pattern = "yyyy-MM-dd"), format dates in JSON

5?? @JsonCreator, allows custom constructor JSON deserialization

6?? @JsonAnySetter, captures extra fields to mapped to properties

7?? @JsonIgnoreProperties(ignoreUnknown = true), ignores unknown JSON fields when deserializing

8?? @JsonUnwrapped, flattens nested objects in JSON

9?? @JsonAlias, supports multiple JSON field names

?? @JsonSetter, specifies a custom setter method for deserialization


?? 6. Real-World Use Cases for JSON Handling

? 1. REST API Communication, JSON is the most common data format for REST APIs

? 2. Data Storage, NoSQL Databases (MongoDB, Firebase) uses JSON for storing documents.

? 3. Configurations, Many applications store configurations in JSON Files (e.g. config.json)

? 4. Message Queues, JSON is widely used in Kafka, RabbitMQ for message-based communication

? 5. Logging & Monitoring, Many logging frameworks (e.g., Logstash, ELK stack) use JSON-formatted logs.


?? 7. Key Takeaways

? ?Jackson is the most popular library for JSON processing in Java

? ?ObjectMapper is the core class for converting JSON ? Java Objects

? Annotations like @JsonIgnore, @JsonProperty help control serialization behavior

? You can convert JSON ? XML easily using XMLMapper

? Mastering JSON handling is essential for working with APIs, databases and messaging systems.

要查看或添加评论,请登录

Marcelo Honorio Santos的更多文章