Java Jackson Serialization ignore specific nested properties with Annotations

安稳与你 提交于 2019-12-11 19:03:21

问题


I'm using jackson (with spring boot) to return some DTOs like json. The problem is that I have specific DTO which contains nested objects, which contains another objects. Can I have ignore some nested properties directly from the DTO, without any Annottations on the nested objects (because they are used in another DTOs)

public class MyDTO {

  private MyObjectA a;

}

public class MyObjectA a {

  private MyNestedObject b;

}

I want when i serialize MyDTO to exclude MyNestedObject b I've tried with @JsonIgnoreProperties, but it not works with nested objects. Can I achieve this mission only with Annotations in the MyDTO class?


回答1:


You might use @JsonView. You need to annotate some nested objects but it is not kind a static thing that then hides everything from other DTOs or so.

For example you could declare following views to use:

public class View {
    public static class AllButMyNestedObject {
    }
    public static class AlsoMyNestedObject 
        extends AllButMyNestedObject {
    }    
}

Then annotating your classes like:

@JsonView(AllButMyNestedObject.class)
public class MyDTO {
    private MyObjectA a;
}

and

public class MyObjectA {
    @JsonView(AlsoMyNestedObject.class)
    private MyNestedObject b;
}

you can decide with mapper what to serialize, like:

ObjectMapper mapper = new ObjectMapper();
String result = mapper
    .writerWithView(View.AlsoMyNestedObject.class)
// OR .writerWithView(View.AllButNestedObject.class)
    .writeValueAsString(myDto);


来源:https://stackoverflow.com/questions/54959144/java-jackson-serialization-ignore-specific-nested-properties-with-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!