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

JavaJSONObject Oriented ProgrammingProgramming

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"
}
raja
Published on 30-Sep-2019 08:23:04
Advertisements