【问题标题】:How does @JsonView annotation can be used for nested entities?@JsonView 注解如何用于嵌套实体?
【发布时间】:2013-11-07 10:43:33
【问题描述】:

我正在尝试对我的嵌套实体使用 @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;

}

让我们尝试从response中用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 注释采用字符串数组,但我应该如何确定这些书面视图类必须为它们所属的每个实体显式工作?我想很快看到 UserView 适用于 User,AddressView 适用于 Address。

谢谢。

【问题讨论】:

    标签: java json jackson jax-rs dropwizard


    【解决方案1】:

    我遇到了类似的问题,这不完全是您的问题,但也许该方法对您有用。

    我只使用一个 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<Object> {
    
        @Override
        public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writerWithView(Views.Low.class).writeValue(jgen, value);
        }
    } 
    

    最后在我的对象中我是这样使用的:

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

    您可以使用这种方法来解决您的问题,但是如果您使用不同的类视图,您必须编写大量的序列化器。

    【讨论】:

    • 像魅力一样工作!如果父母和孩子有不同的观点,在序列化器中要提到的一件事是使用子类的视图。
    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多