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