简体   繁体   中英

Java Jackson Serialization ignore specific nested properties with Annotations

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM