Close

Jackson JSON - Using @JsonAlias Annotation to define property aliases for deserialization

[Updated: Oct 3, 2018, Created: Oct 3, 2018]

@JsonAlias annotation (since version 2.9) can be used to define one or more alternative names for a property which should be mapped during deserialization.

This annotation has no effect during serialization where actual property name is always used.

Example

POJO

package com.logicbig.example;

import com.fasterxml.jackson.annotation.JsonAlias;

public class Employee {
  private String name;
  @JsonAlias({"department", "employeeDept" })
  private String dept;
    .............
}

Deserializing with aliases

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      ObjectMapper om = new ObjectMapper();
      System.out.println("-- deserializing --");
      String jsonData = "{\"name\":\"Trish\",\"department\":\"IT\"}";
      Employee employee = om.readValue(jsonData, Employee.class);
      System.out.println(employee);

      jsonData = "{\"name\":\"Trish\",\"employeeDept\":\"IT\"}";
      employee = om.readValue(jsonData, Employee.class);
      System.out.println(employee);

      System.out.println("-- serializing --");
      Employee e = Employee.of("Jake", "Admin");
      String s = om.writeValueAsString(e);
      System.out.println(s);
  }
}
-- deserializing --
Employee{name='Trish', dept='IT'}
Employee{name='Trish', dept='IT'}
-- serializing --
{"name":"Jake","dept":"Admin"}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.7: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 11
  • Maven 3.5.4

@JsonAlias Example Select All Download
  • jackson-json-alias-annotation
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java

    See Also