@JsonView注释如何用于嵌套实体?
我试图为我的嵌套实体使用@JsonView注释。 更清楚的是,假设我们有2个实体,每个实体都有自己的视图类。
public class JsonViewAddress { //some view classes } public class Address { //fields annotated by JsonViewAddress's classes and @JsonProperty } public class JsonViewPerson { //some view classes } public class Person { //some fields (yes annotated with JsonViewPerson classes and @JsonProperty) //also assume that this is annotated with any JsonViewPerson's class. private Address address; }
让我们尝试用响应中的Json类型来实现这个Person类
@Path("hey") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class Resource { @GET @Path("/stack/overflow") @JsonView(value = { /* WHAT SHOULD BE WRITTEN HERE ? */ }) public Response method() { //return Person entity in response } }
@JsonView注释采用String数组,但我该如何确定这些编写的视图类必须为它们所属的每个实体显式工作? 我想看看UserView适用于User,AddressView适用于Address。
谢谢。
我有类似的问题,这不是你的问题,但也许这种方法对你有用。
我只使用一个ViewObject
public class Views { public static class Low { } public static class Medium extends Low { } public static class High extends Medium { } }
每次我有一个嵌套对象我需要它在Views.Low视图中,所以我写一个序列化器来做到这一点。
public class Serializer extends JsonSerializer
最后,在我的对象中我使用了这样的:
public class Person { @JsonView(Views.High.class) @JsonSerialize(using = Serializer.class) private Address address; }
资源:
@Path("hey") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class Resource { @GET @Path("/stack/overflow") @JsonView(Views.High.class) public Response method() { //return Person entity in response with address low view } @GET @Path("/stack/overflow") @JsonView(Views.Medium.class) public Response method() { //return Person entity in response with no address } }
您可以使用此方法来解决您的问题,但如果使用不同的类视图,则必须编写大量的序列化程序。