Cannot construct instance of `class name` (although at least on Creator exists)

We Are Going To Discuss About Cannot construct instance of `class name` (although at least on Creator exists). So lets Start this Java Article.

Cannot construct instance of `class name` (although at least on Creator exists)

  1. Cannot construct instance of `class name` (although at least on Creator exists)

    You need a constructor with all parameters:
    public SampleRequest(String fromDate, String toDate) { this.fromDate = fromDate; this.toDate = toDate; }

  2. Cannot construct instance of `class name` (although at least on Creator exists)

    You need a constructor with all parameters:
    public SampleRequest(String fromDate, String toDate) { this.fromDate = fromDate; this.toDate = toDate; }

Solution 1

You need a constructor with all parameters:

public SampleRequest(String fromDate, String toDate) {

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

}

Or using @AllArgsConstructor or @Data from lombok.

Original Author Andronicus Of This Content

Solution 2

Hi you need to write custom deserializer as it not able to parse String (fromDate and toDate) to Date

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

this link has a tutorial to get started with custom deserializer https://www.baeldung.com/jackson-deserialization

Deserializer could be written like this.

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);
    }
}}

You can register the deserializer at Class itself like this.

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

Or either you can register custom deserializer manually like this

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

Original Author dextermini Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment