close

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

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Cannot construct instance of class name (although at least on Creator exists) in java. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Cannot construct instance of class name (although at least on Creator exists) Error Occurs?

Today I get the following error Cannot construct instance of class name (although at least on Creator exists) in java.

How To Solve Cannot construct instance of class name (although at least on Creator exists) Error ?

  1. How To Solve Cannot construct instance of class name (although at least on Creator exists) Error ?

    To Solve Cannot construct instance of class name (although at least on Creator exists) Error Or using @AllArgsConstructor or @Data from lombok.

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

    To Solve Cannot construct instance of class name (although at least on Creator exists) Error Or using @AllArgsConstructor or @Data from lombok.

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.

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment