0

I'm trying to map the response of an API to my object:

class Person {
  private Long id;
  private String firstname;
  private String lastname;

  public Person(Long id, String firstname, String lastname)
...

and my api call looks like:

RestTemplate restTemplate = new RestTemplate();
Person person = restTemplate.getForObject("http://xxx/getPerson", Person.class);

Which returns a json that looks like:

{
 "id": 1,
 "firstname": "first",
 "lastname": "last"
}

Unfortunately I'm getting the following error:

Type definition error: [simple type, class xxx.Person]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xxx.Person` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (PushbackInputStream); line: 4, column: 5]

Any idea why? I have a constructor in my class so I'm not too sure why this is throwing an error. Thanks!

Hearen
  • 7,420
  • 4
  • 53
  • 63
Andrew
  • 441
  • 1
  • 7
  • 20

3 Answers3

2

As the exception clearly points out:

(no Creators, like default construct, exist)

You have no default constructor for your class Person.

Any idea why?

Because you explicitly defined a constructor and just due to this behavior, the default constructor will not be generated automatically.

So you should deal with it, and there are two things you need to care about:

  1. providing a default constructor either you defining it explicitly or using an lombok annotation @NoArgsConstructor;
  2. another headsup might be properties mismatching issue, if the json doesn't have all the properties your class defines, you should also ignore them explicitly by @JsonIgnoreProperties(ignoreUnknown = true) to the class or add @JsonIgnore for the extra fields separately.
Hearen
  • 7,420
  • 4
  • 53
  • 63
1

There is no Default Constructor in your Person class, you can create it manually or you can use lombok @NoargConstructor on top of class to create it

Since you declared argument constructor it's your responsibility to create no arg constructor

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

You need to create a default Constructor first. Also, you can use @JsonIgnoreProperties(ignoreUnknown = true) annotation to ignore any other attributes than those defined in the model.

Take a look at this example - https://spring.io/guides/gs/consuming-rest/

royalghost
  • 2,773
  • 5
  • 23
  • 29