我是否需要在类级别,@JsonView({Views.ViewOne.class, Views.ViewTwo.class})
以便在输出响应中具有非注释字段,例如传递给的视图类?z
v
ObjectMapper
在您的实例MapperFeature.DEFAULT_VIEW_INCLUSION
中启用时,您将不需要它。ObjectMapper
此功能默认启用。您可能以某种方式禁用它吗?
这是文档中的引用:
确定没有视图注释的属性是否包含在 JSON 序列化视图中的功能(@JsonView
有关 JSON 视图的更多详细信息,请参阅)。如果启用,将包含未注释的属性;禁用时,它们将被排除在外。
示例 1
让我们考虑以下Example
类:
@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
类的字段:
@Data
public class Example {
@JsonView(Views.Foo.class)
private int a = 1;
@JsonView(Views.Bar.class)
private int b = 2;
private int c = 3;
}
Example
让我们序列化一个使用Foo
视图的实例:
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
:
@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;
}
Example
让我们序列化一个使用Foo
视图的实例:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithView(Views.Foo.class).writeValueAsString(new Example());
它将生成以下 JSON:
{"a":1,"c":3}
Example
现在让我们序列化一个使用Bar
视图的实例:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithView(Views.Bar.class).writeValueAsString(new Example());
它将生成以下 JSON:
{"b":2}