@JsonDeserialize#as 反序列化为子类

@JsonDeserialize#as 反序列化为子类

  • Example
    • Java Object
    • Main class
    • 不使用 @JsonDeserialize#as
  • 原文链接

可使用 @JsonDeserialize#as 指定反序列化的类型为子类型。优先级 using > as

Example

Java Object

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

不使用 @JsonDeserialize#as

不使用 @JsonDeserialize#as 时,rate 会被反序列化为 java.lang.Double

-- 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

原文链接

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

你可能感兴趣的:(Jackson,Jackson,java,json)