【发布时间】:2016-05-26 04:45:42
【问题描述】:
我正在尝试返回 Map 的 JSON 表示形式作为我的控制器中定义的操作的返回类型。
这是方法本身:
@RequestMapping(value = "/executeRetrieve", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public @ResponseBody Map<String, Object> executeAction() {
Map map = new HashMap();
map.put("message", "hello");
return map;
}
但是当我调用该操作时,我不断收到错误 406:
HTTP Status 406 - description: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
这意味着问题与 Spring 转换为 JSON 无关,对吧?
更新 - 这是我的上下文配置:
public class ServletInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ServletConfiguration.class);
context.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
【问题讨论】:
-
发布您的请求标头。您的
produces子句非常具体,通常没有必要(Spring 为您进行内容协商)。另外,你是如何配置你的上下文的——Spring Boot? -
@chrylis 我更新了我的帖子。我已经把配置放在那里了
-
如果你的方法是生成 json,那为什么要返回一个映射而不是一个字符串呢?相信大部分的Java json库都可以把Map对象转成JsonObject,然后转成toString那个
-
@cricket_007 我把它实现为 json.toString()。但是当我尝试使用它时,它没有用。
-
究竟是什么不起作用?我对Spring不太熟悉,但是不应该有一些可以访问的请求参数来获取POST数据吗?
标签: java json spring web-services rest