How can we change a field name in JSON using Jackson in Java?


The Jackson Annotation @JsonProperty is used on a property or method during serialization or deserialization of JSON. It takes an optional ‘nameparameter which is useful in case the property name is different than ‘keyname in JSON. By default, if the key name matches the property name, value is mapped to property value.

In the below example, we can change a field name in JSON using @JsonProperty annotation.

Example

import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonPropertyAnnotationTest {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      User user = new User("Sai", "Adithya", "9959984000", "0402358700");
      String data = mapper.writeValueAsString(user);
      System.out.println(data);
   }
}
// User class
class User {
   @JsonProperty("first-name")
   public String firstName;
   @JsonProperty("last-name")
   public String lastName;
   @JsonProperty("mobile-phone")
   public String mobilePhone;
   @JsonProperty("home_phone")
   public String workPhone;
   public User(String firstName, String lastName, String mobilePhone, String workPhone) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.mobilePhone = mobilePhone;
      this.workPhone = workPhone;
   }
}

Output

{
   "first-name" : "Sai",
   "last-name" : "Adithya",
   "mobile-phone" : "9959984000",
   "home_phone" : "0402358700"
}

Updated on: 06-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements