栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Spring MVC中使用@JsonView

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Spring MVC中使用@JsonView

@JsonView
是已经支持在杰克逊JSON处理器从V1.4开始。

新增编辑:已 针对Jackson 1.9.12更新

根据v1.8.4
文档,我

writevalueUsingView
现在
使用 的函数已被 弃用, 请改用ObjectMapper.viewWriter(java.lang.Class) …但是 从1.9
开始也已 弃用 ,请改用writerWithView(Class) !(请参阅v1.9.9
文档)


因此,这是一个更新的示例,已在Spring 3.2.0和Jackson 1.9.12中进行了测试,由于使用,它们只是返回

{id:1}
而不是扩展。切换到会导致
{name:"name"}``.writerWithView(Views.Public.class)``Views.ExtendPublic.class``{"id":1,"name":"name"}

package com.demo.app;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.prehaus.jackson.map.annotate.JsonView;import org.prehaus.jackson.map.ObjectMapper;import org.prehaus.jackson.map.ObjectWriter;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Controllerpublic class DemoController {    private final ObjectMapper objectMapper = new ObjectMapper();    @RequestMapping(value="/jsonOutput")    @ResponseBody    public String myObject(HttpServletResponse response) throws IOException {        ObjectWriter objectWriter = objectMapper.writerWithView(Views.Public.class);        return objectWriter.writevalueAsString(new MyObject());    }    public static class Views {        static class Public {}        static class ExtendPublic extends Public {}    }    public class MyObject {        @JsonView(Views.Public.class) Integer id = 1;        @JsonView(Views.ExtendPublic.class) String name = "name";    }}

上一页编辑:
您需要实例化

ObjectMapper
和使用自定义视图,如图写出来的物体在这里,或在这个例子:

定义视图:

class Views {    static class Public {}    static class ExtendedPublic extends PublicView {}    ...}public class Thing {    @JsonView(Views.Public.class) Integer id;    @JsonView(Views.ExtendPublic.class) String name;}

使用视图:

private final ObjectMapper objectMapper = new ObjectMapper();@RequestMapping(value = "/thing/{id}")public void getThing(@PathVariable final String id, HttpServletResponse response) {    Thing thing = new Thing();    objectMapper.writevalueUsingView(response.getWriter(), thing, Views.ExtendPublic.class);}

如果您使用Jackson> =
1.7,则可能会发现

@JSONFilter
更适合您的需求。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427594.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号