Java Jackson序列化会忽略带有注释的特定嵌套属性 [英] Java Jackson Serialization ignore specific nested properties with Annotations

查看:124
本文介绍了Java Jackson序列化会忽略带有注释的特定嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用杰克逊(带有弹簧启动)返回一些DTO,例如json.问题是我有特定的DTO,其中包含嵌套的对象,其中包含另一个对象.我是否可以直接从DTO忽略一些嵌套属性,而不必在嵌套对象上添加任何注释(因为它们已在其他DTO中使用)

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;

}

我希望在序列化MyDTO时排除 MyNestedObject b 我尝试使用@JsonIgnoreProperties,但不适用于嵌套对象. 我只能使用MyDTO类中的注释来完成此任务吗?

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?

推荐答案

您可以使用@JsonView.您需要注释一些嵌套对象,但这并不是一种静态的东西,它随后会将所有内容从其他DTO中隐藏起来.

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

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

您可以使用mapper决定要序列化的内容,例如:

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

这篇关于Java Jackson序列化会忽略带有注释的特定嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆