杰克逊无法实例化ArrayList

fwi*_*ind 3 java spring jackson spring-boot

我想发送以下POST请求:

POST: /api/test
{
   "words": ["running", "testing", "and"]
}
Run Code Online (Sandbox Code Playgroud)

我的控制器如下所示:

@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);
}
Run Code Online (Sandbox Code Playgroud)

Words类:

public class Words {

    private List<String> words;

    public Words(List<String> words) {
        this.words = words;
    }

    public List<String> getWords() {
        return words;
    }
}
Run Code Online (Sandbox Code Playgroud)

当发送字符串而不是列表时它工作正常但是使用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]
Run Code Online (Sandbox Code Playgroud)

Ale*_*exR 6

默认情况下,Jackson使用默认构造函数创建类的实例.你没有.所以,要么添加构造函数

public Words() {}
Run Code Online (Sandbox Code Playgroud)

或者使用注释标记现有构造函数@JsonCreator:

@JsonCreator
public Words(@JsonProperty("words") List<String> words) {
    this.words = words;
}
Run Code Online (Sandbox Code Playgroud)

  • 仅当未定义其他构造函数时,才会自动生成默认构造函数.否则你必须明确定义它. (3认同)