我正在使用以下bean定义使我的spring应用程序使用JSON进行对话
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
此消息转换器bean是否可以使用@JsonView注释?
@JsonView是已经支持在杰克逊JSON处理器从V1.4开始。
@JsonView
根据v1.8.4 文档,我writeValueUsingView现在使用 的函数已被弃用,请改用ObjectMapper.viewWriter(java.lang.Class) …但是从1.9开始也已弃用 ,请改用writerWithView(Class)!(请参阅v1.9.9 文档)
writeValueUsingView
因此,这是一个更新的示例,已在Spring 3.2.0和Jackson 1.9.12中进行了测试,由于使用,它们仅返回{id: 1}而不是扩展。切换到会导致{name: "name"}.writerWithView(Views.Public.class)Views.ExtendPublic.class{"id":1,"name":"name"}
{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.codehaus.jackson.map.annotate.JsonView; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public 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和使用自定义视图,如图写出来的物体在这里,或在这个例子:
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更适合你的需求。