@JsonSerialize#as 序列化为超类

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

假如 A extends B:

 @Serialize(as = B.class)
 A a;

序列化时会跳过 A 特有的字段,只序列化 B 拥有的字段。

Example

Java Objects

public class Rectangle {
    private int width;
    private int height;
    ...
}    
public class RoundRectangle extends Rectangle {
    private int arcWidth;
    ...
}    
public class View {
    @JsonSerialize(as = Rectangle.class)
    private RoundRectangle roundRectangle;
    ...
}    

Main class

public class ExampleMain {
    public static void main(String[] args) throws IOException {
        System.out.println("-- Java object to JSON (serialization) --");
        View view = new View();
        view.setRoundRectangle(RoundRectangle.of(5, 7, 2));
        System.out.println("Java object: " + view);

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(view);//the arcWith property will be skipped
        System.out.println("JSON string: " + jsonString);

        System.out.println("-- JSON to Java object (deserialization) --");
        View view2 = om.readValue(jsonString, View.class);
        System.out.println("Java Object: " + view2);
    }
}
-- Java object to JSON (serialization) --
Java object: View{roundRectangle=RoundRectangle{arcWidth=2, width=5, height=7}}
JSON string: {"roundRectangle":{"width":5,"height":7}}
-- JSON to Java object (deserialization) --
Java Object: View{roundRectangle=RoundRectangle{arcWidth=0, width=5, height=7}}

不使用 @JsonSerialize#as

不使用 @JsonSerialize#as 会包含 arcWidth

-- Java object to JSON (serialization) --
Java object: View{roundRectangle=RoundRectangle{arcWidth=2, width=5, height=7}}
JSON string: {"roundRectangle":{"width":5,"height":7,"arcWidth":2}}
-- JSON to Java object (deserialization) --
Java Object: View{roundRectangle=RoundRectangle{arcWidth=2, width=5, height=7}}

原文链接

Jackson JSON - Serializing as supertype using ‘as’ attribute of @JsonSerialize

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值