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

我有以下类,我将其用作请求有效负载:


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]]

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


喵喔喔
浏览 122回答 2
2回答

白猪掌柜的

您需要一个带有所有参数的构造函数:public SampleRequest(String fromDate, String toDate) {&nbsp; &nbsp; this.fromDate = fromDate;&nbsp; &nbsp; this.toDate = toDate;}或使用@AllArgsConstructor或@Data来自龙目岛。

紫衣仙女

您需要编写自定义反序列化器,因为它无法将字符串(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() {&nbsp; &nbsp; this(null);}public CustomDateDeserializer(Class<?> vc) {&nbsp; &nbsp; super(vc);}@Overridepublic Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {&nbsp; &nbsp; String date = jsonparser.getText();&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; return formatter.parse(date);&nbsp; &nbsp; } catch (ParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException(e);&nbsp; &nbsp; }}}您可以像这样在 Class 本身注册反序列化器。@JsonDeserialize(using = ItemDeserializer.class)public class Item {&nbsp; ...}或者您可以像这样手动注册自定义反序列化器ObjectMapper mapper = new ObjectMapper();SimpleModule module = new SimpleModule();module.addDeserializer(Item.class, new ItemDeserializer());mapper.registerModule(module);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java