【问题标题】:How to get JSON as Response in Spring MVC?如何在 Spring MVC 中获取 JSON 作为响应?
【发布时间】:2017-03-22 15:01:19
【问题描述】:

我正在尝试以 JSON 格式返回响应。
搜索后,我找到了在 RequestMapping 中添加 headers = "Accept=application/json" 的解决方案。
但它仍然无法正常工作。
它抛出错误 HTTP 状态 406“此请求标识的资源只能生成具有根据请求“接受”标头不可接受的特征的响应。”
这是我的控制器代码:

@RestController
public class EmployeeController {

    private EmployeeService employeeService;

    @Autowired(required = true)
    @Qualifier(value = "employeeService")
    public void setEmployeeService(EmployeeService employeeService){
        this.employeeService = employeeService;
    }

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String test(){
        return "{\"name\":\"xyz\"}";
    }


    @RequestMapping(value = "/employees",method = RequestMethod.GET,headers = "Accept=application/json")
    public  List<Employee> listEmployees(){
        List<Employee> employees = this.employeeService.getEmployees();
        return employees;
    }
}

我哪里做错了?

【问题讨论】:

  • 在添加 headers="Accept=application/json" 之前遇到了什么问题?
  • 我认为您可能正在寻找的是“生产”/“消费”,具体取决于您是否想接收或生产 json 数据。您可以在这里阅读:docs.spring.io/spring/docs/current/javadoc-api/org/…
  • 例如:RequestMapping(value = "/api", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
  • 请提供minimal reproducible example。同时向我们展示您将请求发送到的 URL。
  • 谢谢大家solution为我工作:)

标签: java spring web-services spring-mvc


【解决方案1】:

生成 JSON、XML 响应的简单方法是 @ResponseBody 注解。

@RequestMapping(value =" /jsonPostSingle", method = RequestMethod.GET)
 @ResponseBody
 public PostModel generateJSONPostsingle(@ModelAttribute("postModel") PostModel postModel) {

 if(postModel.getPostId() == 1) {
 postModel.setTitle("post title for id 1");
 } else {
 postModel.setTitle("default post title");
 }
 return postModel;
 }

这样您就可以使用@ModelAttribute 将您的请求映射到模型类。

按照完整教程Spring MVC : JSON response using @ResponseBody

【讨论】:

    【解决方案2】:

    我了解到您正在尝试发送来自 /employees 的 GET 请求的响应。

    如果您使用的是 Spring 3.1,请尝试使用

    @RequestMapping(value = "/employees",method = RequestMethod.GET, produces = "application/json")
    

    而不是添加headers = "Accept=application/json"

    更多信息: 如果要指定将随请求发送的数据类型,可以使用 consumes 属性

    示例:

    @RequestMapping(value="/foo", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    

    这将仅使用 JSON 类型进行消费和响应

    查看这个关于春季更新的链接http://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements/

    希望对你有帮助

    【讨论】:

    • 不知道为什么大家都转发我的答案?
    • 问候,我打开了这个问题并输入了答案,却没有注意到你在评论帖子。我只知道我何时添加了答案并重新加载了页面。 @Alex Karlsson
    • @Alex 你没有发布答案。您对问题发表了评论。
    • 您为什么认为produces 的行为与headers 不同?
    • 老实说,我只知道它对语法进行了更新,但它可以对用户产生特定类型的响应。无论如何,我找到了描述良好的答案here。你可以看看 :) @Sotirios Delimanolis
    猜你喜欢
    • 2015-12-28
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2017-07-27
    • 2011-05-11
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多