Search code examples
jsonspringresttemplate

Optional nested JSON object with Spring RestTemplate


In the API I'm trying to use with Spring RestTemplate I'm receiving an optional field as shown in the example below. This optional field is a nested object and I would like to use a nested class to map it.

{
  "name": "John",
  "age": 30
}
{
  "name": "John",
  "age": 30,
  "car": {
    "year": 1984,
    "color": "red"
  }
}

My current class definition:

public class User {
    public class Car {
        @Getter
        @Setter
        public String color;

        @Getter
        @Setter
        public Integer year;
    }

    @Getter
    @Setter
    public String name;

    @Getter
    @Setter
    public Integer age;

    @Getter
    @Setter
    public Car car;
}

With the invocation:

ResponseEntity<User> response = restTemplate.exchange("http://....", HttpMethod.POST, request, User.class);

I get the following exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of '....User$Car' (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor

How could I have the car property either null or instantiated with Car class if the node is present in the json?


Solution

  • Could you try with the below updated class. Change is defining the inner class as static.

    public  class User {
        public static class Car {
            @Getter
            @Setter
            public String color;
    
            @Getter
            @Setter
            public Integer year;
        }
    
        @Getter
        @Setter
        public String name;
    
        @Getter
        @Setter
        public Integer age;
    
        @Getter
        @Setter
        public Car car;
    }