I am using Spring MVC via Spring Boot 1.2.
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
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. 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.
So, what are my options for fixing this problem?
Thank you.
Annotate your Person
constructor parameter with @JsonProperty
.
public Person(@JsonProperty("name") String name) {
this.name = name;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.