如何在Spring MVC中将正确的JSON传递给控制器​​?

我无法弄清楚为什么在将POST请求传递给http://localhost:8080/company时我得到HTTP 415

我在POST请求中的JSON

 { "id" : 7, "name" : "IBM" } 

这是我在控制器中的方法

 @Controller @RequestMapping("/company") public class CompanyController { @Autowired CompanyRepository companyRepository; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Collection getAll() { return companyRepository.getCompanies(); } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public String add(@RequestBody Company company) { companyRepository.save(company); return "redirect:/company"; } } 

而我的实体

 @Entity @Table(name = "company") public class Company implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column private String name; @JsonIgnore @OneToMany(mappedBy = "company") @LazyCollection(LazyCollectionOption.FALSE) private Collection employees; 

任何想法如何解决它?

UPD:

响应消息: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

您会注意到您的方法已注释

 @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) 

consumes是对@RequestMapping的限制,表示此方法仅处理具有application/json Content-Type of application/json请求。 您的请求似乎没有该标头。 你需要添加它。