Class 和字段级@JsonView 注释和对象映射器

Class and field level @JsonView annotation and Object Mapper

我有 viewsentity class 如下所示:

class Views{
   class ViewOne{}
   class ViewTwo{}
}

class Test{

   @JsonView({Views.ViewOne.class})
   public int x;

   @JsonView({Views.ViewTwo.class})
   public int y;

   public int z;

   public int v;
}

我的问题是,我是否需要在 class 级别设置 @JsonView({Views.ViewOne.class, Views.ViewTwo.class}),以便我在输出响应中具有非注释字段,如 z, v,而不管视图 Class 传递给对象映射器?

我确实尝试查看有关使用 class 级别 @JsonView 注释 的不同资源,但我找不到任何资源。有什么作用吗?如果是,请做同样的解释。

Do I need to have @JsonView({Views.ViewOne.class, Views.ViewTwo.class}) at class level so that I have non-annotated fields like z, v in the output response irrespective of view class passed to ObjectMapper?

ObjectMapper 实例中启用 MapperFeature.DEFAULT_VIEW_INCLUSION 时,您将不需要它。默认情况下启用此功能。可能你以某种方式禁用了它?

引用文档中的一段话:

Feature that determines whether properties that have no view annotations are included in JSON serialization views (see @JsonView for more details on JSON Views). If enabled, non-annotated properties will be included; when disabled, they will be excluded.


示例 1

让我们考虑以下 Example class:

@Data
public class Example {

    private int a = 1;

    private int b = 2;

    private int c = 3;
}

让我们将 Example 的实例序列化为 JSON 使用:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Foo());

它将产生以下 JSON:

{"a":1,"b":2,"c":3}

示例 2

现在让我们考虑以下观点:

public class Views {

    public static class Foo {}

    public static class Bar {}
}

让我们将视图应用到 Example class 的字段:

@Data
public class Example {

    @JsonView(Views.Foo.class)
    private int a = 1;

    @JsonView(Views.Bar.class)
    private int b = 2;

    private int c = 3;
}

然后让我们使用 Foo 视图序列化 Example 的一个实例:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithView(Views.Foo.class).writeValueAsString(new Example());

它将产生以下 JSON:

{"a":1,"c":3}

现在让我们禁用默认视图包含并再次序列化它:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
String json = mapper.writerWithView(Views.Foo.class).writeValueAsString(new Example());

它将产生以下 JSON:

{"a":1}

示例 3

现在让我们在 Example class 中使用以下视图配置:

@Data
@JsonView(Views.Foo.class)
public static class Example {

    private int a = 1;

    @JsonView(Views.Bar.class)
    private int b = 2;

    private int c = 3;
}

然后让我们使用 Foo 视图序列化 Example 的一个实例:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithView(Views.Foo.class).writeValueAsString(new Example());

它将产生以下 JSON:

{"a":1,"c":3}

现在让我们使用 Bar 视图序列化 Example 的一个实例:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithView(Views.Bar.class).writeValueAsString(new Example());

它将产生以下 JSON:

{"b":2}