[英]POST to Spring MVC controller results in “HttpMessageNotReadableException: Could not read JSON: No suitable constructor found”
I am using Spring MVC via Spring Boot 1.2. 我正在通过Spring Boot 1.2使用Spring MVC。
I have a model that looks like this: 我有一个看起来像这样的模型:
public class Person {
final private String name;
/*
* Cannot include this constructor because `name` is `final`.
*
public Person() {}
*/
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And this RestController
: 而这个
RestController
:
@RestController
public class PeopleController {
@RequestMapping(value = "/person", method = RequestMethod.POST, consumes = "application/json")
public Person createPerson(@RequestBody Person person) {
return person;
}
}
I'd like the framework to take the name
attribute of the JSON object I POST, and use that to construct my Person
instance. 我希望框架采用我发布的JSON对象的
name
属性,并使用该属性来构造我的Person
实例。 But, when I try to POST to this controller like, 但是,当我尝试发布到该控制器时,
$ curl -XPOST -d '{ "name": "Dmitry" }' -H 'Content-Type: application/json' localhost:8080/person
I get this error: 我收到此错误:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: No suitable constructor found for type [simple type, class example.Person]: can not instantiate from JSON object (need to add/enable
type information?)
at [Source: java.io.PushbackInputStream@4e7fa67d; line: 1, column: 3]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class example.Person]:
can not instantiate from JSON object (need to add/enable type information?)
// Trace ommitted
Searching on the Web, people say I need to include an empty constructor. 人们在网上搜索时说我需要包含一个空的构造函数。 But I can't do that, given the nature of my model, which has
final
properties that need to be set in the constructor. 但是鉴于模型的性质,我无法做到这一点,因为模型的
final
属性需要在构造函数中设置。
So, what are my options for fixing this problem? 那么,解决该问题有哪些选择?
Thank you. 谢谢。
Annotate your Person
constructor parameter with @JsonProperty
. 使用
@JsonProperty
注释您的Person
构造函数参数。
public Person(@JsonProperty("name") String name) {
this.name = name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.