2015-06-17 108 views
0

問題很簡單: 如何解析xml文件,像這樣到POJO?Spring RestTemplate。如何解析服務器對POJO的XML響應

XML

<ArrayOfiDealIssuerCountry xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Aspider.iDeal.Domain"> 
<iDealIssuerCountry> 
<CountryNames>CountryName</CountryNames> 
<Issuers> 
<iDealIssuer> 
    <ID>1</ID> 
    <Name>Bank A</Name> 
</iDealIssuer> 
<iDealIssuer> 
    <ID>2</ID> 
    <Name>Bank B</Name> 
</iDealIssuer> 
</Issuers> 
</iDealIssuerCountry> 
</ArrayOfiDealIssuerCountry> 

什麼我現在已經是

要求:

ArrayList<Issuers> issuers = restTemplate.exchange(builder.build().encode().toString(),HttpMethod.GET, 
       entity, new ParameterizedTypeReference<ArrayList<Issuers>>(){}).getBody(); 

性反應:

[Issuers [countryName=null, issuers=[]]] 

Issuers.java:

@XmlRootElement(name = "iDealIssuerCountry") 
public class Issuers { 

    @XmlElement(name = "CountryNames", required = true) 
String countryNames; 

    @XmlElement(name = "Issuers", required = true) 
ArrayList<Issuer> issuers = new ArrayList<Issuer>(); 
/// getters and setters 
} 

Issuer.java:

@XmlRootElement(name = "iDealIssuer") 
@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(propOrder = {"ID", "Name"}) 
    public class Issuer { 
    @XmlElement(name = "ID", required = true) 
    Long id; 

    @XmlElement(name = "Name", required = true) 
    String name; 
// getters and setters 
} 

響應體是未來:

[ 
    { 
    "CountryNames":"CountryName", 
    "Issuers": 
     [ 
      {"ID":1,"Name":"Bank A"}, 
      {"ID":2,"Name":"Bank B"} 
     ] 
    } 
    ] 

我想我失去了一些東西在XML文檔映射到Java類。 任何人都可以指出我的錯誤嗎?

+0

哦我的!抱歉。 P.S不工作的遲到傢伙 – partTimeNinja

回答

0

解決:

我批註我的POJO的構造是這樣的:

@JsonCreator 
    public IssuersCountry(@JsonProperty("CountryNames") String CountryNames,@JsonProperty("Issuers") ArrayList<Issuer> issuers) {...} 

和反序列化使用:

List<IssuersCountry> issuers = new ObjectMapper().readValue(responseBody, new TypeReference<List<IssuersCountry>>(){});