【发布时间】:2017-02-23 10:10:07
【问题描述】:
我试图在 POST 方法中解析一个简单的对象,但我总是收到此错误:
2017-02-23 03:52:45 DEBUG AnnotationMethodHandlerExceptionResolver:133 - Resolving exception from handler [com.dlo.food.controller.Lists@40079d7e]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
2017-02-23 03:52:45 DEBUG ResponseStatusExceptionResolver:133 - Resolving exception from handler [com.dlo.food.controller.Lists@40079d7e]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
2017-02-23 03:52:45 DEBUG DefaultHandlerExceptionResolver:133 - Resolving exception from handler [com.dlo.food.controller.Lists@40079d7e]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
在我的 pom.xml 中,我包含了 jackson 库文件:
...
<properties>
<jackson.version>2.6.3</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
...
我已经这样声明了控制器:
/**
*
* @param request
* @return
* @return
*/
@ResponseBody
@RequestMapping(value = "/uiupdatepost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> UIUpdatePost(@RequestBody Category category, @RequestHeader HttpServletRequest request) {
try {
return ResponseEntity.ok("");
} catch (Throwable t) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new UIError(t).toHTML());
}
}
类分类很简单:
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public Category() {
//
}
private String id;
private String name;
private String priority;
private String categoryId;
private String color;
/**
ALL GETTER AND SETTERS
**/
}
如果我运行 CURL:
curl -H "Content-Type: application/json" -X POST -d '{"id":"1","name":"PIZZA","priority":"1","color":"","categoryId":""}' http://localhost:8080/food/uiupdatepost.html
我收到此错误:
HTTP:415
我已经搜索了所有可能的解决方案,包括:
- 删除 consumes 属性。
- 检查了 2 个名称相同但类型不同的 setter。不,所有属性都有 1 个 setter/1 个 getter。
还测试了手动反序列化没有问题:
Category userFromJSON = mapper.readValue("{\"id\":\"1\",\"name\":\"PIZZA\",\"priority\":\"1\",\"color\":\"\",\"categoryId\":\"\"}", Category.class);
【问题讨论】:
-
在控制器类上方使用@RestController。
标签: java json spring spring-mvc jackson