I created a Mock service that return JSON response as below :
{ "RegionsID": "123", "RegionsName": "TestRegion", "DistrictList": [ { "DistrictsID": "321" }, { "DistrictsName": "TestDistrict" } ] }
Then i created the GetRegionsDistrictsRestClient class to consume the REST API using restTemplate :
public class GetRegionsDistrictsRestClient {
private Logger logger = Logger.getLogger(getClass().getName());
@Autowired
public RegionRequestHeader getRegionDistrict() {
String theUrl = "https://a03e1a89-0363-4b17-8e3c-eb0220020e9b.mock.pstmn.io/GetRegionsDistricts";
RestTemplate restTemplate = new RestTemplate();
RegionRequestHeader result = restTemplate.getForObject(theUrl, RegionRequestHeader.class);
return result;
}
}
The RegionRequestHeader and DistrictRequestHeader are like this :
public class RegionRequestHeader {
private Integer regionsID;
private String regionsName;
private List<DistrictRequestHeader> districtList;
public Integer getRegionsID() {
return regionsID;
}
public void setRegionsID(Integer regionsID) {
this.regionsID = regionsID;
}
public String getRegionsName() {
return regionsName;
}
public void setRegionsName(String regionsName) {
this.regionsName = regionsName;
}
public List<DistrictRequestHeader> getDistrictList() {
return districtList;
}
public void setDistrictList(List<DistrictRequestHeader> districtList) {
this.districtList = districtList;
}
}
public class DistrictRequestHeader {
private Integer districtsID;
private String districtsName;
public Integer getDistrictsID() {
return districtsID;
}
public void setDistrictsID(Integer districtsID) {
this.districtsID = districtsID;
}
public String getDistrictsName() {
return districtsName;
}
public void setDistrictsName(String districtsName) {
this.districtsName = districtsName;
}
}
The Response is ok but the values are null as mentioned on screenshot :
Since you have a different property name within the class. Spring automatic deserialization won't map the fields correctly with the response JSON structure.
If this is the response body
{ "RegionsID": "123", "RegionsName": "TestRegion", "DistrictList": [ { "DistrictsID": "321" }, { "DistrictsName": "TestDistrict" } ] }
Then, You need to define JSON property names explicitly in the class
public class RegionRequestHeader {
@JsonProperty("RegionsID")
private Integer regionsID;
@JsonProperty("RegionsName")
private String regionsName;
@JsonProperty("DistrictList")
private List<DistrictRequestHeader> districtList;
// Getters & Setters
}
Similarly,
public class DistrictRequestHeader {
@JsonProperty("DistrictsID")
private Integer districtsID;
@JsonProperty("DistrictsName")
private String districtsName;
//Getters & Setters
}