无法构造“类名”的实例(尽管至少存在于Creator中)

时间:2019-03-06 21:18:06

标签: java jackson

我有以下课程,正在用作请求有效负载:

public class SampleRequest {

    private String fromDate;
    private String toDate;

    // Getters and setters removed for brevity.
}

我正在尝试将其与下面的资源结合使用(只是尝试将其打印到屏幕上以查看发生的事情):

@PostMapping("/getBySignatureOne")
public ResponseEntity<?> getRequestInfo(@Valid @RequestBody SampleRequest signatureOneRequest) {

    System.out.println(signatureOneRequest.getToDate);
    System.out.println(signatureOneRequest.getFromDate);
}

这是我发送的JSON请求:

{
    "fromDate":"2019-03-09",
    "toDate":"2019-03-10"
}

这是我得到的错误:

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.test.app.payload.SampleRequest` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('fromDate'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.test.app.payload.SampleRequest` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('fromDate')
 at [Source: (PushbackInputStream); line: 1, column: 2]]

我很想知道这里出了什么问题,我怀疑这是构造函数的问题,或者我在某处缺少一些注释,但是老实说,我不确定自己哪里出了问题。

2 个答案:

答案 0 :(得分:1)

嗨,您需要编写自定义解串器,因为它无法将String(fromDate和toDate)解析为Date

  

{       “ fromDate”:“ 2019-03-09”,       “ toDate”:“ 2019-03-10”   }

此链接包含一个教程,可让您开始使用自定义解串器https://www.baeldung.com/jackson-deserialization

反序列化器可以这样写。

public class CustomDateDeserializer extends StdDeserializer<Date> {

private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

public CustomDateDeserializer() {
    this(null);
}

public CustomDateDeserializer(Class<?> vc) {
    super(vc);
}

@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {
    String date = jsonparser.getText();
    try {
        return formatter.parse(date);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}}

您可以像这样在Class本身上注册反序列化器。

@JsonDeserialize(using = ItemDeserializer.class)
public class Item {  ...}

或者您可以像这样手动注册自定义反序列化器

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Item.class, new ItemDeserializer());
mapper.registerModule(module);

答案 1 :(得分:0)

您需要具有所有参数的构造函数:

public SampleRequest(String fromDate, String toDate) {

    this.fromDate = fromDate;
    this.toDate = toDate;

}

或者使用龙目岛的@AllArgsConstructor@Data