因此,我使用的是Spring Boot 1.5.3,並嘗試使用以下Json的一部分 - - 即AccountId
和Username
- (實際上,它是一個oData v2接口從角色的SAP NetWeaver實例得到)爲一類使用restTemplate.exchange:Spring Resttemplate:使用@JsonIgnore解析導致值爲空
{
"d":{
"__metadata":{
"id":"...",
"uri":"...",
"type":"...."
},
"AccountID":"0100000001",
"Username":"[email protected]",
"Partners":{
"__deferred":{
"uri":"Navigationproperty"
}
}
}
}
我班建立這樣的,因爲一開始我只是想獲得帳戶ID,名稱:
@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{
public PortalAccount() {
}
@JsonProperty("AccountID")
public String accountID;
@JsonProperty("Username")
public String username;
public String getPortalAccountID() {
return accountID;
}
public void setPortalAccountID(String portalAccountID) {
this.accountID = portalAccountID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "Account{" +
"accountID='" + accountID + '\'' +
", username='" + username +'\'' +
'}';
}
}
以下是我嘗試cal的方式l在:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
ObjectMapper mapper = new ObjectMapper();
PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);
我第一次嘗試分析它直接像使用ResponseEntity<PortalAccount>
的文檔,但這只是導致一個空的類(帳戶= NULL,用戶名= NULL),所以我想上面使用ResponseEntity<String>
方式看看我在將響應解析爲字符串表示時得到的內容。這樣,我可以確保上面的json被正確地返回,它是這樣的。因此,值肯定存在,它必須是解析的問題,但我很遺憾沒有解決這個問題。
我希望你能幫助我在這裏!
編輯:作爲一個答案提到,getForObject可能會工作,但這導致我的其他問題,因爲我不得不使用基本身份驗證,所以它不是真正可行的。我也嘗試套管問題,命名變量accountID或AccountID,它沒有解決。
我的猜測是,問題是JSON中包含AccountId和Username的對象「d」。這實際上將轉換爲名爲「d」的類,其中包含字符串「AccountId」和「用戶名」。出於測試目的,嘗試命名您的類「d」而不是PortalAccount。 –
另外,嘗試@JsonTypeName(「d」)類PortalAccount –
所以,是的,getBody()包含我添加到問題的json。現在我嘗試將課程更改爲「d」,這導致了相同的行爲。另外,我嘗試將JsonTypeName(「d」)添加到'd'-Class和重新生成的PortalAccount-Class中,但沒有成功:/ –