杰克逊无法实例化 ArrayList
Jackson cant instantiate ArrayList
我想发送以下 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);
}
单词class:
public class Words {
private List<String> words;
public Words(List<String> words) {
this.words = words;
}
public List<String> getWords() {
return words;
}
}
当发送字符串而不是列表时它工作正常但是对于列表我收到以下错误:
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]
默认情况下,Jackson 使用默认构造函数创建 class 的实例。你没有。所以,要么添加构造函数
public Words() {}
或者使用注释标记现有构造函数@JsonCreator
:
@JsonCreator
public Words(@JsonProperty("words") List<String> words) {
this.words = words;
}
我想发送以下 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);
}
单词class:
public class Words {
private List<String> words;
public Words(List<String> words) {
this.words = words;
}
public List<String> getWords() {
return words;
}
}
当发送字符串而不是列表时它工作正常但是对于列表我收到以下错误:
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]
默认情况下,Jackson 使用默认构造函数创建 class 的实例。你没有。所以,要么添加构造函数
public Words() {}
或者使用注释标记现有构造函数@JsonCreator
:
@JsonCreator
public Words(@JsonProperty("words") List<String> words) {
this.words = words;
}