Search code examples
jsonspringspring-bootrestresttemplate

Spring RestTemplate response body is null when trying to parse JSON


I've been trying many solutions from similar solved problems in this page but I can't make it work. I'm making a get petition to obtain an array JSON, and I want to map those values into my class.

I got this class:

public class Devices {

    private String DeviceName;
    private String DeviceDescription;

    public String getDeviceName() {
        return DeviceName;
    }

    public void setDeviceName(String deviceName) {
        this.DeviceName = deviceName;
    }

    public String getDeviceDescription() {
        return DeviceDescription;
    }

    public void setDeviceDescription(String deviceDescription) {
        this.DeviceDescription = deviceDescription;
    }

}

The GET petition returns this JSON below:

[{"DeviceName":"AMIXT-20EC-VIDM0000","DeviceDescription":"Samsung device "},{"DeviceName":"AMIXT-E0F9-VIDM0001","DeviceDescription":"Tablet Huawei"}]

I've tried solutions like this one (also tried with getForObject):

ResponseEntity<Devices[]> responseEntity = restTemplate.getForEntity(url, Devices[].class);

As we can see in this photo, the body properties are null

What am I missing?


Solution

  • The issue is related to the name of the fields in the JSON, name start with an upper-case letter.

    One simple solution would be to use @JsonProperty annotation on the variables defined in the Devices class

    public class Devices {
    
        @JsonProperty("DeviceName")
        private String deviceName;
    
        @JsonProperty("DeviceDescription")
        private String deviceDescription;
    
        public String getDeviceName() {
            return deviceName;
        }
    
        public void setDeviceName(String deviceName) {
            this.deviceName = deviceName;
        }
    
        public String getDeviceDescription() {
            return deviceDescription;
        }
    
        public void setDeviceDescription(String deviceDescription) {
            this.deviceDescription = deviceDescription;
        }
    }