我想发送以下POST请求:
POST: /api/test
{
"words": ["running", "testing", "and"]
}
我的控制器如下所示:
@RequestMapping(value={"/api/test"}, method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<Text> getWords(@RequestBody Words words) {
// Do something with words...
return new ResponseEntity<Text>(new Text("test"), HttpStatus.OK);
}
词类:
public class Words {
private List<String> words;
public Words(List<String> words) {
this.words = words;
}
public List<String> getWords() {
return words;
}
}
当发送字符串而不是List时,它工作正常但是对于List我得到以下错误:
Could not read document:
No suitable constructor found for type [simple type, class api.models.tokenizer.Words]: can not instantiate from JSON object (need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@60f2a08; line: 2, column: 5]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class api.models.tokenizer.Words]: can not instantiate from JSON object (need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@60f2a08; line: 2, column: 5]
答案 0 :(得分:6)
默认情况下,Jackson使用默认构造函数创建类的实例。你没有。所以,要么添加构造函数
public Words() {}
或使用注释@JsonCreator
标记现有构造函数:
@JsonCreator
public Words(@JsonProperty("words") List<String> words) {
this.words = words;
}