【问题标题】:Using @JsonView in Spring MVC 4 + jackson 2.5在 Spring MVC 4 + jackson 2.5 中使用 @JsonView
【发布时间】:2015-10-30 19:34:30
【问题描述】:

我将使用 Spring MVC 4.0.4、Hibernate 4.3.5 和 Jackson 2.5.4 开发 JSON REST 服务。对于控制器,我需要@JsonView 来过滤属性。

我已经用@JsonView(View.Summary.class)@JsonView(View.Details.class) 注释了模型的一些属性。当我注释控制器以过滤其结果时(使用@JsonView(View.Summary.class)),它返回所有带注释的属性而不考虑传递的视图类(View.Summary.class)。

查看课程:

public class View {
    public static interface Summary{}
    public static interface Details extends Summary{}
}

型号:

@Entity
@Table(name="image")
public class Image {

    @JsonView(View.Summary.class)
    private int id;
    private String thumbnailURL;

    @JsonView(View.Details.class)
    private String imageURL;
    private Date registrationDate;
    private int price;

    //..... getters and setters
}

控制器:

@JsonView(View.Summary.class)
@RequestMapping(method = RequestMethod.GET, value = "/service/images")
public  List<Image> getAllImages(HttpServletResponse response) {
        List<Image> list;
        // codes for fetching the result 
        return list;
}

Spring 消息转换器:

<mvc:message-converters>
         <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> 
         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.digimind.utils.HibernateAwareObjectMapper">
                </bean>
            </property>
        </bean> 
    </mvc:message-converters>

HibenrateAwareObjectMapper:

public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {

        Hibernate4Module hm = new Hibernate4Module();
        registerModule(hm);
        this.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
        this.disable(MapperFeature.AUTO_DETECT_GETTERS);

    }
}

结果:

    [
       {
          "id": 3,
          "imageURL": "url3"
       },
       {
          "id": 2,
          "imageURL": "url 2"
       }
   ]

预期结果:

    [
       {
          "id": 3,
       },
       {
          "id": 2,
       }
   ]

感谢您的关注。

【问题讨论】:

    标签: java spring spring-mvc jackson json-view


    【解决方案1】:

    我认为您的继承发生了倒退。您在控制器上的注释要求使用 View.Summary.class 注释的所有内容。字段 imageUrl 使用 @JsonView(View.Details.class) 进行注释。鉴于 View.Details 扩展了 View.Summary,任何 View.Details 类型的对象都与 View.Summary 具有 is-a 关系,因此它是从您的 RestController 返回的。我相信您需要像这样定义视图:

    public class View {
        public static interface Details {}
        public static interface Summary extends Details {}
    }
    

    现在,摘要字段是 - 一个详细字段,但一个详细字段不是 - 一个摘要字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 2011-11-30
      • 2019-02-27
      • 2015-07-25
      • 2018-12-23
      • 2020-07-03
      • 2014-07-03
      • 1970-01-01
      相关资源
      最近更新 更多