【问题标题】:Jackson cant instantiate ArrayList杰克逊无法实例化 ArrayList
【发布时间】:2023-04-02 07:10:01
【问题描述】:

我想发送以下 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;
    }
}

发送字符串而不是列表时,它可以正常工作,但是使用列表时出现以下错误:

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]

【问题讨论】:

    标签: java spring jackson spring-boot


    【解决方案1】:

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

    public Words() {}
    

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

    @JsonCreator
    public Words(@JsonProperty("words") List<String> words) {
        this.words = words;
    }
    

    【讨论】:

    • 谢谢,成功了。但是默认构造函数不是在没有声明的时候自动生成的吗?例如,即使没有显式声明默认构造函数,调用 Words words = new Words(); 也可以工作。为什么杰克逊不使用这个生成的默认构造函数?
    • 只有在没有定义其他构造函数时才会自动生成默认构造函数。否则你必须明确定义它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多