【发布时间】:2017-11-09 00:30:05
【问题描述】:
所以,我正在使用 Spring Boot 1.5.3 并尝试使用以下 Json 的一部分 - 即 AccountId 和 Username- (实际上,它是从 SAP Netweaver 实例获取的 oData v2 接口)使用 restTemplate.exchange 进入一个类:
{
"d":{
"__metadata":{
"id":"...",
"uri":"...",
"type":"...."
},
"AccountID":"0100000001",
"Username":"test@test.com",
"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 +'\'' +
'}';
}
}
这是我尝试称呼它的方式:
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> 直接解析它,但这只会导致一个空类(accountid = null,username = null),所以我尝试使用上述方法使用ResponseEntity<String> 看看什么我只是将响应解析为字符串表示形式。这样,我可以确保正确返回上面的 json,它就是这样。所以,这些值肯定存在,它必须是解析的问题,但遗憾的是我没有解决这个问题。
希望你能帮帮我!
编辑:正如一个答案提到的,getForObject 可能有效,但这会给我带来其他问题,因为我必须使用基本身份验证,所以它不是真的可行。我还尝试了大小写问题,命名变量 accountID 或 AccountID ,但没有成功。
【问题讨论】:
-
我的猜测是,问题是 JSON 中包含 AccountId 和 Username 的对象“d”。这实际上将转换为一个名为“d”的类,其中包含字符串“AccountId”和“Username”。出于测试目的,请尝试将您的类命名为“d”而不是 PortalAccount。
-
另外,在 PortalAccount 类上尝试@JsonTypeName("d")
-
所以,是的,getBody() 包含我添加到问题中的 json。现在我尝试将类更改为“d”,这会导致相同的行为。另外,我尝试将 JsonTypeName("d") 添加到
d-Class 和重新重构的 PortalAccount-Class 中,但没有成功:/ -
好的,所以我可能弄错了,您必须将“d”包装在另一个类中,以便您拥有一个包含“d”类型作为属性的类,就像现在一样。同样,出于测试目的。
标签: java json spring-boot jackson resttemplate