Jackson
JSON
field name change
Java
serialization

How to change a field name in JSON using Jackson

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

When working with JSON data in Java applications, Jackson is a powerful library that facilitates serialization and deserialization of JSON objects. Occasionally, you might need to change the name of a field in a JSON object to maintain compatibility with different API specifications or to adapt to naming conventions. In this article, we will delve into how to change a field name in JSON using the Jackson library, covering technical aspects and providing examples.

Jackson Overview

Jackson is a suite of data-processing tools for Java that includes the following:

  • ObjectMapper: The core component that enables conversion between Java objects and JSON.
  • Annotations: Simplify the configuration of serialization and deserialization processes.
  • Modules and Extensions: Enhance Jackson's capabilities with additional features.

JSON field name customization is typically achieved by leveraging Jackson annotations, allowing seamless remapping of field names during object binding.

Renaming JSON Fields

Using @JsonProperty Annotation

The @JsonProperty annotation is one of the simplest ways to change the field name while serializing or deserializing JSON data.

java
1import com.fasterxml.jackson.annotation.JsonProperty;
2
3public class User {
4    private String originalName;
5
6    public User(@JsonProperty("original_name") String originalName) {
7        this.originalName = originalName;
8    }
9
10    @JsonProperty("original_name")
11    public String getOriginalName() {
12        return originalName;
13    }
14
15    public void setOriginalName(String originalName) {
16        this.originalName = originalName;
17    }
18}

Explanation

  • Constructor Argument: By using @JsonProperty("original_name") on the constructor, Jackson maps the JSON field original_name to the originalName property during deserialization.
  • Getter Method: Similarly, applying @JsonProperty("original_name") on the getter method ensures that serialization converts the originalName property to original_name.

Serializing and Deserializing

To serialize and deserialize using ObjectMapper, follow these steps:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2
3public class Main {
4    public static void main(String[] args) throws Exception {
5        ObjectMapper mapper = new ObjectMapper();
6
7        // Serialize
8        User user = new User("JohnDoe");
9        String jsonString = mapper.writeValueAsString(user);
10        System.out.println("Serialized JSON: " + jsonString);
11
12        // Deserialize
13        String inputJson = "{\"original_name\":\"JaneDoe\"}";
14        User deserializedUser = mapper.readValue(inputJson, User.class);
15        System.out.println("Deserialized User: " + deserializedUser.getOriginalName());
16    }
17}

Expected Output

 
Serialized JSON: {"original_name":"JohnDoe"}
Deserialized User: JaneDoe

Advanced Considerations

Using Mix-ins

If it's not possible to modify the source class or if you want a non-intrusive approach, use Jackson mix-ins. A mix-in is an abstract class or interface used to add annotations without altering the target class.

java
1import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
2import com.fasterxml.jackson.databind.annotation.JsonSerialize;
3
4// Define mix-in
5public abstract class UserMixIn {
6    UserMixIn(@JsonProperty("original_name") String originalName) {}
7
8    @JsonProperty("original_name")
9    abstract String getOriginalName();
10}
11
12// Apply mix-in
13ObjectMapper mapper = new ObjectMapper();
14mapper.addMixIn(User.class, UserMixIn.class);

Practical Example

java
1public class Main {
2    public static void main(String[] args) throws Exception {
3        ObjectMapper mapper = new ObjectMapper();
4        mapper.addMixIn(User.class, UserMixIn.class);
5
6        // Serialization
7        User user = new User("AliceSmith");
8        String jsonString = mapper.writeValueAsString(user);
9        System.out.println("Serialized JSON with Mix-in: " + jsonString);
10
11        // Deserialization
12        String inputJson = "{\"original_name\":\"BobJohnson\"}";
13        User deserializedUser = mapper.readValue(inputJson, User.class);
14        System.out.println("Deserialized User with Mix-in: " + deserializedUser.getOriginalName());
15    }
16}

Expected Output

 
Serialized JSON with Mix-in: {"original_name":"AliceSmith"}
Deserialized User with Mix-in: BobJohnson

Summary Table

FeatureApproachAdvantages
Basic Renaming@JsonPropertySimple and intuitive Directly on class
Non-Intrusive RenamingMix-insAllows for separation of concerns
Custom Serialization RulesCustom Serializer/Deserializer annotationsControl over serialization logic

Conclusion

Changing JSON field names in a Java application with Jackson can be achieved using various methods to suit different use cases. Whether through @JsonProperty, mix-ins, or other advanced serialization techniques, Jackson provides flexibility and control over JSON processing. By understanding and utilizing these tools, developers can efficiently manage JSON data within their projects.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.