Spring RestTemplate. How to parse server XML response to POJOs

7.3k views Asked by At

question is simple : How can i parse xml document like this to POJO?

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>

what i have now is

request:

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

Responce:

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

response body is next :

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

I think i'm missing something in mapping of xml doc to java class. Can anyone point my mistake?

2

There are 2 answers

0
John On

Look into JAXB. More information is available here:

http://www.oracle.com/technetwork/articles/javase/index-140168.html

0
partTimeNinja On

Resolved:

I've annotated my POJO's constructor's like this:

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

and for deserialization used :

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