我正在使用以下 bean 定义使我的 spring 应用程序使用 JSON 进行通信
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
这个消息转换器 bean 是否可以使用 @JsonView 注释?
最佳答案
@JsonView
是 already supported从 v1.4 开始在 Jackson JSON 处理器中。
新编辑为 Jackson 1.9.12 更新
根据 v1.8.4 documentation我使用 writeValueUsingView
的函数现在已弃用 改用 ObjectMapper.viewWriter(java.lang.Class) ...... 然而这也 已弃用 从 1.9 开始,改用 writerWithView(Class)! (参见 v1.9.9 documentation)
所以这是一个更新的示例,使用 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.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
并使用自定义 View 写出对象,如图所示 here ,或者在这个例子中:
定义 View :
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;
}
使用 View :
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
更符合您的需求。
关于java - 在 Spring MVC 中使用@JsonView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772304/