【问题标题】:Spring - Return JSON from MapSpring - 从地图返回 JSON
【发布时间】: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


【解决方案1】:

从一开始就做了我应该做的事。 Spring 可以为我们将一个对象渲染成 JSON。因此,出于一致性、组织和基本面向对象编程的问题,我创建了一个模型类,其中包含作为响应所需的所有属性,并让 Spring 处理呈现。这是我的最终代码:

@RequestMapping(value = "/executeRetrieve", method = RequestMethod.POST)
public @ResponseBody Student executeRetrieve(HttpServletRequest request) {
    String user = request.getParameter("user");
    String password = request.getParameter("password");

    return loginService.executeRetrieve(user, password);
}

谢谢大家。

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多