Reputation: 47
I want to get data from an API it gives me XML data like this
I can map the last of these to an object. See the code bellow:
public void getCurrencies() {
XmlMapper xmlMapper = new XmlMapper();
Currency currency = null;
try {
currency = xmlMapper.readValue(
new URL("https://www.lb.lt/webservices/FxRates/FxRates.asmx/getCurrentFxRates?tp=eu"),
Currency.class);
CurrencyBase c = currency.getCurrencyBase();
CurrencyAmount d = c.getCurrencyAmount();
System.out.println(d.getName());
} catch (Exception e) {
System.out.println(e);
}
}
But how do I parse the XML data to a list of objects?
My model for the currency:
@JacksonXmlRootElement(localName = "FxRates")
public class Currency {
@JacksonXmlProperty(localName = "FxRate")
@JacksonXmlElementWrapper(useWrapping = true)
private CurrencyBase currencyBase;
public class CurrencyBase {
@JacksonXmlProperty(localName = "Tp")
private String type;
@JacksonXmlProperty(localName = "Dt")
private String date;
@JacksonXmlProperty(localName = "CcyAmt")
@JacksonXmlElementWrapper(useWrapping = true)
private CurrencyAmount currencyAmount;
public class CurrencyAmount {
@JacksonXmlProperty(localName = "Ccy")
private String Name;
@JacksonXmlProperty(localName = "Amt")
private String ConvertionRate;
Upvotes: 0
Views: 443
Reputation: 539
You need use TypeReference to map the List of Objects. You have list of CurrencyBase rather than Currency itself. Here is the code changes to make it work:
public void getCurrencies() {
XmlMapper xmlMapper = new XmlMapper();
List<CurrencyBase> currency = null;
try {
currency = xmlMapper.readValue(
new URL("https://www.lb.lt/webservices/FxRates/FxRates.asmx/getCurrentFxRates?tp=eu"),
new TypeReference<List<CurrencyBase>>(){});
System.out.println(currency);
} catch (Exception e) {
System.out.println(e);
}
}
Also have to change @JacksonXmlElementWrapper(useWrapping = false) and change CurrencyAmount to List :
public class CurrencyBase {
@JacksonXmlProperty(localName = "Tp")
private String type;
@JacksonXmlProperty(localName = "Dt")
private String date;
@JacksonXmlProperty(localName = "CcyAmt")
@JacksonXmlElementWrapper(useWrapping = false)
private List<CurrencyAmount> currencyAmount;
}
Upvotes: 2