Close

Jackson JSON - Deserializing as a subtype using 'as' attribute of @JsonDeserialize

[Updated: Jun 2, 2018, Created: Jun 2, 2018]

The attribute @JsonDeserialize#as can be used to to deserialize to a specific subtype of declared type of a Java object.

When serializing, Jackson will by default use the specific runtime type, but during deserializing time Jackson cannot determined the actual intended runtime type of a super type without @JsonDeserialize#as.

Example

Java Object

In this example we will assign Number to BigDecimal before serialization.

package com.logicbig.example;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.math.BigDecimal;

public class CurrencyRate {
  private String pair;

  @JsonDeserialize(as = BigDecimal.class)
  private Number rate;
    .............
}

Main class

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      System.out.println("-- Java object to JSON (serialization) --");
      CurrencyRate cr = new CurrencyRate();
      cr.setPair("USD/JPY");
      cr.setRate(new BigDecimal(109.15).setScale(2, RoundingMode.CEILING));
      System.out.println("Java object: " + cr);

      ObjectMapper om = new ObjectMapper();
      String s2 = om.writeValueAsString(cr);
      System.out.println("JSON string: " + s2);

      System.out.println("-- JSON to Java object (deserialization) --");
      CurrencyRate cr2 = om.readValue(s2, CurrencyRate.class);
      System.out.println("Java Object: " + cr2);
      System.out.println("rate type: "+cr2.getRate().getClass());
  }
}
-- Java object to JSON (serialization) --
Java object: CurrencyRate{pair='USD/JPY', rate=109.16}
JSON string: {"pair":"USD/JPY","rate":109.16}
-- JSON to Java object (deserialization) --
Java Object: CurrencyRate{pair='USD/JPY', rate=109.16}
rate type: class java.math.BigDecimal

Without @JsonDeserialize#as

If we don't use @JsonDeserialize(as = BigDecimal.class) i.e.

public class CurrencyRate {
  private String pair;
  private Number rate;
 .....
}

then output will be:

-- Java object to JSON (serialization) --
Java object: CurrencyRate{pair='USD/JPY', rate=109.16}
JSON string: {"pair":"USD/JPY","rate":109.16}
-- JSON to Java object (deserialization) --
Java Object: CurrencyRate{pair='USD/JPY', rate=109.16}
rate type: class java.lang.Double

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.5: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.3.9

@JsonDeserialize#as example Select All Download
  • jackson-deserialize-as
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also