使用 restTemplate 来自 REST API 的空响应值

Null response values from REST API using restTemplate

我创建了一个模拟服务,return JSON 响应如下:

{ "RegionsID": "123", "RegionsName": "TestRegion", "DistrictList": [ { "DistrictsID": "321" }, { "DistrictsName": "TestDistrict" } ] }

然后我创建了 GetRegionsDistrictsRestClient class 以使用 restTemplate 使用 REST API :

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

}

RegionRequestHeader 和 DistrictRequestHeader 是这样的:

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

}

响应正常,但如屏幕截图所示,值为空:

因为您在 class 中有不同的 属性 名称。 Spring 自动反序列化不会将字段正确映射到响应 JSON 结构。

如果这是响应正文

{ "RegionsID": "123", "RegionsName": "TestRegion", "DistrictList": [ { "DistrictsID": "321" }, { "DistrictsName": "TestDistrict" } ] }

然后,您需要在 class

中明确定义 JSON 属性 名称
public class RegionRequestHeader {

@JsonProperty("RegionsID")
private Integer regionsID;

@JsonProperty("RegionsName")
private String regionsName;

@JsonProperty("DistrictList")
private List<DistrictRequestHeader> districtList;

// Getters & Setters
}

同样,

public class DistrictRequestHeader {
 @JsonProperty("DistrictsID")
 private Integer districtsID;

 @JsonProperty("DistrictsName")
 private String districtsName;
 //Getters & Setters
}