您的当前位置:首页正文

@JsonSerialize#as 序列化为超类

2024-11-25 来源:个人技术集锦

可使用 @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}}

原文链接

显示全文