I have this soap response below and I need to parse it to a java object ...But all the fields are returning null when I print it. Below the classes that I am using to interpret the response.
I have been trying to use jaxb to unmarshall the content but none of my tries went right.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns2:consultarPosicaoCotistaOnOfflineFundoResponse>
<ns2:listCotistaFundo>
<ns2:cotistaFundo>
<ns2:cdFundo>014588</ns2:cdFundo>
<ns2:nmCliente>BRADESCO FIC FIM GAVEA MACRO</ns2:nmCliente>
<ns2:dtPosicao>2021-02-18</ns2:dtPosicao>
<ns2:vlCota>1.3121393</ns2:vlCota>
<ns2:qtdCotas>43650.7211055</ns2:qtdCotas>
<ns2:vlCorrigido>57275.83</ns2:vlCorrigido>
<ns2:vlIr>221.1</ns2:vlIr>
<ns2:vlIof>0</ns2:vlIof>
<ns2:vlLiquidoResg>57054.73</ns2:vlLiquidoResg>
<ns2:vlContaCorrente>57054.73</ns2:vlContaCorrente>
<ns2:vlContaInvestimento>57054.73</ns2:vlContaInvestimento>
<ns2:noCnpjFundo>28428211000149</ns2:noCnpjFundo>
<ns2:icAfPosicao>F</ns2:icAfPosicao>
<ns2:vlAplicacao>49069.11</ns2:vlAplicacao>
<ns2:qtCotasBloqueadas>0</ns2:qtCotasBloqueadas>
<ns2:vlBrutoBloqueado>0</ns2:vlBrutoBloqueado>
<ns2:vlLiquidoBloqueado>0</ns2:vlLiquidoBloqueado>
<ns2:vlAplicacaoNaoCotizada>0</ns2:vlAplicacaoNaoCotizada>
<ns2:vlResgateNaoCotizado>0</ns2:vlResgateNaoCotizado>
</ns2:cotistaFundo>
</ns2:listCotistaFundo>
<ns3:responseMessages>
<ns3:message>
<ns3:code>EJCOT-0000</ns3:code>
<ns3:desc>Operação Concluída</ns3:desc>
</ns3:message>
</ns3:responseMessages>
</ns2:consultarPosicaoCotistaOnOfflineFundoResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Unmarshaller unmarshaller = JAXBContext.newInstance(ConsultarPosicaoCotistaOnOfflineFundoResponse.class).createUnmarshaller();
response = (ConsultarPosicaoCotistaOnOfflineFundoResponse) unmarshaller.unmarshal(soapMessage.getSOAPBody().extractContentAsDocument());
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "consultarPosicaoCotistaOnOfflineFundoResponse",
namespace = "http://totvs.cot.webservices")
public class ConsultarPosicaoCotistaOnOfflineFundoResponse implements Serializable {
private ListCotistaFundo[] listCotistaFundo;
public ListCotistaFundo[] getCotistaFundo() {
return listCotistaFundo;
}
#XmlElement(name ="listCotistaFundo",
namespace = "http://totvs.cot.webservices")
public void setCotistaFundos(ListCotistaFundo[] listCotistaFundo) {
this.listCotistaFundo = listCotistaFundo;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class ListCotistaFundo {
#XmlElement(name = "cdFundo")
private String cdFundo;
#XmlElement(name = "nmCliente")
private String nmCliente;
#XmlElement(name = "dtPosicao")
private Date dtPosicao;
#XmlElement(name = "vlCota")
private BigDecimal vlCota;
#XmlElement(name = "qtdCotas")
private BigDecimal qtdCotas;
#XmlElement(name = "vlCorrigido")
private BigDecimal vlCorrigido;
#XmlElement(name = "vlIr")
private BigDecimal vlIr;
#XmlElement(name = "vlIof")
private BigDecimal vlIof;
#XmlElement(name = "vlLiquidoResg")
private BigDecimal vlLiquidoResg;
#XmlElement(name = "vlContaCorrente")
private BigDecimal vlContaCorrente;
#XmlElement(name = "vlContaInvestimento")
private BigDecimal vlContaInvestimento;
#XmlElement(name = "noCnpjFundo")
private double noCnpjFundo;
#XmlElement(name = "icAfPosicao")
private String icAfPosicao;
#XmlElement(name = "vlAplicacao")
private BigDecimal vlAplicacao;
#XmlElement(name = "qtCotasBloqueadas")
private BigDecimal qtCotasBloqueadas;
#XmlElement(name = "vlBrutoBloqueado")
private BigDecimal vlBrutoBloqueado;
#XmlElement(name = "vlLiquidoBloqueado")
private BigDecimal vlLiquidoBloqueado;
#XmlElement(name = "vlAplicacaoNaoCotizada")
private BigDecimal vlAplicacaoNaoCotizada;
#XmlElement(name = "vlResgateNaoCotizado")
private BigDecimal vlResgateNaoCotizado;
Getters and Setters ...
Does anyone have a tip in how to convert the response in Java object?
It could be an issue with namespace since I dont see namespaces declared in the XML. You could try setting the namespace as empty in both #XmlRootElement and #XmlElement as follows :
#XmlRootElement(name = "consultarPosicaoCotistaOnOfflineFundoResponse",
namespace = "")
#XmlElement(name ="listCotistaFundo", namespace = "")
Related
I am trying to consume api which returns XML.
The api url: api
This is how my XML classes looks:
#XmlRootElement(name="ArrayOfExchangeRatesTable")
#XmlAccessorType(XmlAccessType.FIELD)
public class RootElement {
#XmlElement(name="ExchangeRatesTable")
private TableRateModel tableRateModel;
#XmlAccessorType(XmlAccessType.FIELD)
public class TableRateModel {
#XmlElement(name="Table")
private String table;
#XmlElement(name="EffectiveDate")
private Date effectiveDate;
#XmlElement(name="Rates")
private List<RateModel> rates;
#XmlAccessorType(XmlAccessType.FIELD)
public class RateModel {
#XmlElement(name="Currency")
private Currency currency;
#XmlElement(name="Code")
private String code;
#XmlElement(name="Mid")
private Double mid;
Then in the end I printed it and get a result as:
RootElement{tableRateModel=TableRateModel{table='A', effectiveDate=Thu Jul 20 00:00:00 CEST 2017, rates=[RateModel{currency=null, code='null', mid=null}]}}
Why the list of Rates is null?
The problem is that the XML-elements Rate is wrapped inside a element named Rates. I tested the following classes and got it to work
#XmlRootElement(name = "ArrayOfExchangeRatesTable")
#XmlAccessorType(XmlAccessType.FIELD)
public class RootElement {
#XmlElement(name = "ExchangeRatesTable")
private TableRateModel tableRateModel;
}
#XmlAccessorType(XmlAccessType.FIELD)
class TableRateModel {
#XmlElement(name = "Table")
private String table;
#XmlElement(name = "EffectiveDate")
private Date effectiveDate;
#XmlElement(name = "Rates")
private Rates rates;
}
#XmlAccessorType(XmlAccessType.FIELD)
class Rates {
#XmlElement(name = "Rate")
private List<Rate> rates;
}
#XmlAccessorType(XmlAccessType.FIELD)
class Rate {
#XmlElement(name = "Currency")
private String currency;
#XmlElement(name = "Code")
private String code;
#XmlElement(name = "Mid")
private Double mid;
}
Currency is apparently not serializable because it doesn't have a parameterless contructor. One workaround is to add a getter that returns a Currency, parsed from the String:
#XmlAccessorType(XmlAccessType.FIELD)
class Rate {
#XmlElement(name = "Currency")
private String currency;
#Xml Element(name = "Code")
private String code;
#XmlElement(name = "Mid")
private Double mid;
public Currency getCurrency() {
return Currency.getInstance(currency);
}
}
I have just started to learn how to make a java object from a XML. However, now I have a tricky input and I don't really know how to solve it.
This is the input:
<?xml version="1.0" encoding="UTF-8"?>
<return>
<productChange cd_product="711" ds_product="MBL40337 I151 BLACK P" cd_species="UN" cd_tipi="61062000" cd_cst="5" qt_weight="" cd_nbm="" dt="2016-05-04 11:47:36">
<productvalue cd_company="1" cd_product="711" tp_value="P" cd_value="1" vl_product="61.39">
<tipovaluePrd tp_value="P" cd_value="1" ds_value="SALE" cd_corrency="1" />
</productvalue>
<productvalue cd_company="1" cd_product="711" tp_value="P" cd_value="4" vl_product="129.8">
<tipovaluePrd tp_value="P" cd_value="4" ds_value="SALE STORE" cd_corrency="1" />
</productvalue>
<productvalue cd_company="1" cd_product="711" tp_value="P" cd_value="5" vl_product="64.9">
<tipovaluePrd tp_value="P" cd_value="5" ds_value="SALE AT" cd_corrency="1" />
</productvalue>
<productvalue cd_company="1" cd_product="711" tp_value="P" cd_value="8" vl_product="122.78">
<tipovaluePrd tp_value="P" cd_value="8" ds_value="SALE FQ" cd_corrency="1" />
</productvalue>
</productChange>
</return>
To consume this xml with JaxB (XML provided by a third party company) I have built the following classes:
#XmlAccessorType(XmlAccessType.FIELD)
public class ProductUpdateResponse {
#XmlAttribute(name = "cd_product")
private Integer productCode;
#XmlAttribute(name = "ds_product")
private String productDescription;
#XmlAttribute(name = "cd_species")
private String productSpecie;
#XmlAttribute(name = "cd_tipi")
private Integer productTIPI;
#XmlAttribute(name = "cd_cst")
private Integer productCST;
#XmlAttribute(name = "qt_weight")
private String productWeight;
#XmlAttribute(name = "cd_nbm")
private String productNBM;
#XmlAttribute(name = "dt")
private String productDate;
#XmlElement(name = "productvalue")
private ProductValueType productValue;
// getters and setters
}
#XmlAccessorType(XmlAccessType.FIELD)
public class ProductValue {
#XmlAttribute(name = "cd_product")
private Integer productCode;
#XmlAttribute(name = "cd_company")
private Integer companyCode;
#XmlAttribute(name = "tp_value")
private String valueType;
#XmlAttribute(name = "cd_value")
private Integer valueCode;
#XmlAttribute(name = "vl_product")
private BigDecimal productValue;
#XmlElement(name = "tipovaluePrd")
private ProductValueType productValueType;
//getters and seters
}
#XmlAccessorType(XmlAccessType.FIELD)
public class ProductValueType {
#XmlAttribute(name = "tp_value")
private String valueType;
#XmlAttribute(name = "cd_value")
private String valueCode;
#XmlAttribute(name = "ds_value")
private String valueDescription;
#XmlAttribute(name = "cd_corrency")
private Integer valueCurrency;
//getters and seters
}
However, the main information, for me, is comming as null (productvalue) I wonder if it is because there are four tags productvalue in the xml (I just need the one whose tipovaluePrd.cd_value is 4 ).
Below is the method I'm using to parse the XML:
private ProductUpdateResponse buildResponse(String rawResponse, Class<T> responseClass) {
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(responseClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(rawResponse);
return (ProductUpdateResponse) unmarshaller.unmarshal(reader);
} catch (JAXBException | ClassCastException e) {
return null;
}
}
So, I wonder if there is a way to read specifically the value I want (productvalue element that has tipovaluePrd.cd_value = 4) and how could I do that. If there isn't, how should I build my class so I can read properly everything?
Changing the input is not an option here...
Thanks in advance for any help.
I'm actually surprised you're getting a result from JAXB with your current setup.
You lack a class representing your root element :
#XmlRootElement(name="return")
#XmlAccessorType(XmlAccessType.FIELD)
public class Return {
#XmlElement(name="productchange")
private ProductUpdateResponse response;
//getters and setters
}
Also, in your ProductUpdateResponse class, you should change :
#XmlElement(name = "productvalue")
private ProductValueType productValue;
by
#XmlElement(name = "productvalue")
private List<ProductValue> productValues;
Finally, in your buildResponse method, make sure the responseClass argument is Return.class.
With this, you should have a list with all your productvalue element. You just have to get the productvalue your interested in from it.
If you only want to get the element you're interested with :
As swasa suggested it, you can use the javax.xml.xpath to make an Xpath request on your XML.
If you're willing to change your JAXB Implementation : EclipseLink JAXB Implementation implements an #XmlPath annotation that allows you to bind objects according to an XPath request :
#XmlPath(name = "productvalue/tipovaluePrd[#cd_value=4]")
private ProductValueType productValueType;
I am sending a request to a webservice but it seems the request is invalid. I am sending a similar request using SoapUI and the webservice accepts it. I need to change my request to what SoapUI sends. How can I add namespaces to my request? WSDL is here.
I visited following pages but could not find a solution yet. 1,2,3
Code
SearchFlights
#XmlRootElement(name = "SearchFlights")
#XmlAccessorType(XmlAccessType.FIELD)
public class SearchFlights {
#XmlElement(name = "SoapMessage")
private SoapMessage soapMessage;
getter and setter
SoapMessage
#XmlRootElement(name = "SoapMessage")
#XmlAccessorType(XmlAccessType.FIELD)
public class WegoloSoapMessage {
#XmlElement(name = "Username")
private String username;
#XmlElement(name = "Password")
private String password;
#XmlElement(name = "LanguageCode")
private String languageCode;
#XmlElement(name = "Request")
private Request request;
getters and setters
Request
#XmlRootElement(name = "Request")
#XmlAccessorType(XmlAccessType.FIELD)
public class Request {
#XmlElement(name = "Departure")
private String departure;
#XmlElement(name = "Destination")
private String destination;
#XmlElement(name = "DepartureDate")
private String departureDate;
#XmlElement(name = "ReturnDate")
private String returnDate;
#XmlElement(name = "NumADT")
private int numADT;
#XmlElement(name = "NumINF")
private int numInf;
#XmlElement(name = "NumCHD")
private int numCHD;
#XmlElement(name = "CurrencyCode")
private String currencyCode;
#XmlElement(name = "WaitForResult")
private boolean waitForResult;
#XmlElement(name = "NearByDepartures")
private boolean nearByDepartures;
#XmlElement(name = "NearByDestinations")
private boolean nearByDestinations;
#XmlElement(name = "RROnly")
private boolean rronly;
#XmlElement(name = "MetaSearch")
private boolean metaSearch;
getters and setters
jaxb.index
SearchFlights
Flight
Flights
Leg
Legs
Outbound
Request
Response
WegoloSoapMessage
Code to send request
try {
SaajSoapMessageFactory soapMsgFac = new SaajSoapMessageFactory(
MessageFactory.newInstance());
soapMsgFac.afterPropertiesSet();
WebServiceTemplate webServiceTemplate = new WebServiceTemplate(
soapMsgFac);
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.myprojet.flights.wegolo");
marshaller.afterPropertiesSet();
webServiceTemplate.setMarshaller(marshaller);
webServiceTemplate.setUnmarshaller(marshaller);
webServiceTemplate.afterPropertiesSet();
Response response = (Response) webServiceTemplate
.marshalSendAndReceive(
"http://www5v80.elsyarres.net/service.asmx",
searchFlights,
new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message)
{
((SoapMessage)message).setSoapAction("ElsyArres.API/SearchFlights");
}
}
);
Response msg = (Response) response;
System.err.println("Wegolo >>>"
+ msg.getFlights().getFlight().size());
} catch (Exception s) {
s.printStackTrace();
}
}
My Request
SoapUI request
In your request there is no namesapce before elements like in request from SoapUI.
For example your element:
<SearchFlights>
SoupUI element:
<els:SearchFlights>
You should add namespace xmlns:els="ElsyArres.API" and prefix before all elements using code form here or here or here.
I am receiving following response and am trying to to parse it using JAXB but following code returns IndexOutOfBoundsException.
I am not sure whats wrong with the code. I am suspicious of TotalChargeable and Reckratetotal, tried to have them as separate classes but did not help.
EasytobookResponse response = restTemplate.postForObject(
url, easy, EasytobookResponse.class);
System.err.println("RESPONSE >>>>"
+ response.getResponse().getHotelInfo().get(0).getId());
#XmlRootElement(name = "EasytobookResponse")
#XmlAccessorType(XmlAccessType.FIELD)
public class EasytobookResponse {
#XmlAttribute(name = "target")
private String target;
#XmlAttribute(name = "username")
private String username;
#XmlElement(name = "Response")
private Response response;
getters and setters
#XmlRootElement(name = "Response")
#XmlAccessorType(XmlAccessType.FIELD)
public class Response {
#XmlElementWrapper(name="Hotelinfo")
#XmlElement(name="Hotelinfo")
private List<Hotel> hotelInfo;
getters and setters
#XmlRootElement(name = "Hotel")
#XmlAccessorType(XmlAccessType.FIELD)
public class Hotel {
#XmlElement(name = "Id")
private int id;
#XmlElement(name = "FacilityGroups")
private FacilityGroups facilityGroups;
#XmlElement(name = "exact")
private int exact;
#XmlElementWrapper(name = "Roomtype")
#XmlElement(name = "Roomtype")
private List<Roomtype> roomType;
getters and setters
#XmlRootElement(name = "FacilityGroups")
#XmlAccessorType(XmlAccessType.FIELD)
public class FacilityGroups {
#XmlElement(name = "HandicapFacilities")
private int handicapFacilities;
#XmlElement(name = "HasInternet")
private int hasInternet;
#XmlElement(name = "HasParking")
private int hasParking;
#XmlElement(name = "PetsAllowed")
private int petsAllowed;
#XmlElement(name = "HasChildDiscount")
private int hasChildDiscount;
#XmlElement(name = "HasSwimmingPool")
private int hasSwimmingPool;
#XmlElement(name = "HasAirCon")
private int hasAirCon;
#XmlElement(name = "HasFitnessFacilities")
private int hasFitnessFacilities;
#XmlElement(name = "NonSmoking")
private int nonSmoking;
getters and setters
#XmlRootElement(name = "Roomtype")
#XmlAccessorType(XmlAccessType.FIELD)
public class Roomtype {
#XmlAttribute(name = "parentid")
private String parentid;
#XmlElement(name = "Roomid")
private long roomId;
#XmlElement(name = "Roomname")
private String roomName;
#XmlElement(name = "Capacity")
private int capacity;
#XmlElement(name = "Available")
private int available;
#XmlElement(name = "Totalrate")
private double totalRate;
#XmlAttribute(name="currency")
private String currency;
#XmlAttribute(name="EUR")
#XmlElement(name = "TotalTaxesAndFees")
private double totalTaxesAndFees;
#XmlElement(name = "TotalChargeable")
private double totalChargeable;
#XmlElement(name = "Reckratetotal")
private double reckRateTotal;
#XmlElement(name = "Breakfast")
private int breakfast;
#XmlElement(name = "Booklink")
private String bookLink;
#XmlElement(name = "Hoteldetailslink")
private String hotelDetailsLink;
#XmlElement(name = "Rtoken")
private String rToken;
#XmlElement(name = "Specialoffers")
private String specialOffers;
#XmlElement(name = "Bookingconditions")
private BookingConditions bookingConditions;
#XmlElement(name = "Rateinfo")
private RateInfo rateInfo;
getters and setters
#XmlRootElement(name = "Bookingconditions")
#XmlAccessorType(XmlAccessType.FIELD)
public class BookingConditions {
#XmlElement(name = "Bookable")
private int bookable;
#XmlElement(name = "Chargepoint")
private String chargePoint;
#XmlElement(name = "Requirements")
private Requirement requirement;
getters and setters
#XmlRootElement(name = "Requirements")
#XmlAccessorType(XmlAccessType.FIELD)
public class Requirement {
#XmlElement(name = "Capacity")
private int capacity;
#XmlElement(name = "Creditcardcvc")
private int creditCardCvc;
#XmlElement(name = "Billingaddress")
private int billingAddress;
getters and setters
#XmlRootElement(name = "Rateinfo")
#XmlAccessorType(XmlAccessType.FIELD)
public class RateInfo {
#XmlElement(name = "Underoccupancy")
private int underoccupancy;
#XmlElement(name = "Earlybooking")
private int earlyBooking;
#XmlElement(name = "Lastminutebooking")
private int lastMinuteBooking;
#XmlElement(name = "Nonrefundable")
private int nonRefundable;
#XmlElement(name = "Breakfastincluded")
private int breakfastIncluded;
getters and setters
Response
<?xml version="1.0" encoding="UTF-8"?>
<EasytobookResponse>
<Response target="test" username="project121">
<Hotelinfo>
<Hotel>
<Id>436924</Id>
<FacilityGroups>
<HandicapFacilities>0</HandicapFacilities>
<HasInternet>1</HasInternet>
<HasParking>1</HasParking>
<PetsAllowed>0</PetsAllowed>
<HasChildDiscount>0</HasChildDiscount>
<HasSwimmingPool>0</HasSwimmingPool>
<HasAirCon>1</HasAirCon>
<HasFitnessFacilities>0</HasFitnessFacilities>
<NonSmoking>1</NonSmoking>
</FacilityGroups>
<exact>436924</exact>
<Roomtype>
<Roomid parentid="2069840686">2069840686</Roomid>
<Roomname>Two Persons Standard + Breakfast</Roomname>
<Capacity>2</Capacity>
<Available>8</Available>
<Totalrate currency="AUD" EUR="1204.3398">1800</Totalrate>
<TotalTaxesAndFees currency="AUD" EUR="0">0
</TotalTaxesAndFees>
<TotalChargeable currency="AUD" EUR="1204.3398">1800
</TotalChargeable>
<Reckratetotal currency="AUD" EUR="1204.3398">1800
</Reckratetotal>
<Breakfast>1</Breakfast>
<Booklink>https://stage-site.easytobook.us/booking_screen.php?hotel_id=436924&exact=436924&city_id=23&arrival=20-11-2016&departure=29-11-2016¤cy=EUR&lang=en&room[2069840686]=1&persons=2&rooms=1&amu=280828207&utm_source=project121&utm_medium=affiliate&utm_term=Sydney&utm_content=etb5&utm_campaign=en&rtoken=1VSwnz7whjuxw-RGo5aP6cp-XmdDQSHC7twXmVrwPejOzYDFXdGY_bdbs9xbHuP8xU83qSmzJGz_vgQZHjeE5kVENJkuPBAtuKd6jTqIWCk,
</Booklink>
<Hoteldetailslink>http://stage-site.easytobook.us/hotel_proxy.php?hotel_id=436924&lang=en&arrival=20-11-2016&departure=29-11-2016¤cy=EUR&prs_arr%5B0%5D=2&amu=280828207&utm_source=project121&utm_medium=affiliate&utm_term=Sydney&utm_content=etb5&utm_campaign=en&rtoken=1VSwnz7whjuxw-RGo5aP6cp-XmdDQSHC7twXmVrwPejOzYDFXdGY_bdbs9xbHuP8xU83qSmzJGz_vgQZHjeE5kVENJkuPBAtuKd6jTqIWCk,
</Hoteldetailslink>
<Rtoken>1VSwnz7whjuxw-RGo5aP6cp-XmdDQSHC7twXmVrwPejOzYDFXdGY_bdbs9xbHuP8xU83qSmzJGz_vgQZHjeE5kVENJkuPBAtuKd6jTqIWCk,
</Rtoken>
<Specialoffers />
<Bookingconditions>
<Bookable>1</Bookable>
<Chargepoint>hotel</Chargepoint>
<Requirements>
<Capacity>1</Capacity>
<Creditcardcvc>1</Creditcardcvc>
<Billingaddress>1</Billingaddress>
</Requirements>
</Bookingconditions>
<Rateinfo>
<Underoccupancy>0</Underoccupancy>
<Earlybooking>0</Earlybooking>
<Lastminutebooking>0</Lastminutebooking>
<Nonrefundable>0</Nonrefundable>
<Breakfastincluded>1</Breakfastincluded>
</Rateinfo>
</Roomtype>
<Roomtype>
<Roomid parentid="1379794752">1379794752</Roomid>
<Roomname>Two Persons Superior + Breakfast</Roomname>
<Capacity>2</Capacity>
<Available>4</Available>
<Totalrate currency="AUD" EUR="1264.5568">1890</Totalrate>
<TotalTaxesAndFees currency="AUD" EUR="0">0
</TotalTaxesAndFees>
<TotalChargeable currency="AUD" EUR="1264.5568">1890
</TotalChargeable>
<Reckratetotal currency="AUD" EUR="1264.5568">1890
</Reckratetotal>
<Breakfast>1</Breakfast>
<Booklink>https://stage-site.easytobook.us/booking_screen.php?hotel_id=436924&exact=436924&city_id=23&arrival=20-11-2016&departure=29-11-2016¤cy=EUR&lang=en&room[1379794752]=1&persons=2&rooms=1&amu=280828207&utm_source=project121&utm_medium=affiliate&utm_term=Sydney&utm_content=etb5&utm_campaign=en&rtoken=ocGkvI7xuJJwz1BWWYNBztr7n-__tI8fVNfz3cZsrwRMGrtuHAEGziCH-0poK2ZoveEs-4Fz1_Y4U8pwE4KGKjJc4iwdSKM4ewIJwMU8omA,
</Booklink>
<Hoteldetailslink>http://stage-site.easytobook.us/hotel_proxy.php?hotel_id=436924&lang=en&arrival=20-11-2016&departure=29-11-2016¤cy=EUR&prs_arr%5B0%5D=2&amu=280828207&utm_source=project121&utm_medium=affiliate&utm_term=Sydney&utm_content=etb5&utm_campaign=en&rtoken=ocGkvI7xuJJwz1BWWYNBztr7n-__tI8fVNfz3cZsrwRMGrtuHAEGziCH-0poK2ZoveEs-4Fz1_Y4U8pwE4KGKjJc4iwdSKM4ewIJwMU8omA,
</Hoteldetailslink>
<Rtoken>ocGkvI7xuJJwz1BWWYNBztr7n-__tI8fVNfz3cZsrwRMGrtuHAEGziCH-0poK2ZoveEs-4Fz1_Y4U8pwE4KGKjJc4iwdSKM4ewIJwMU8omA,
</Rtoken>
<Specialoffers />
<Bookingconditions>
<Bookable>1</Bookable>
<Chargepoint>hotel</Chargepoint>
<Requirements>
<Capacity>1</Capacity>
<Creditcardcvc>1</Creditcardcvc>
<Billingaddress>1</Billingaddress>
</Requirements>
</Bookingconditions>
<Rateinfo>
<Underoccupancy>0</Underoccupancy>
<Earlybooking>0</Earlybooking>
<Lastminutebooking>0</Lastminutebooking>
<Nonrefundable>0</Nonrefundable>
<Breakfastincluded>1</Breakfastincluded>
</Rateinfo>
</Roomtype>
</Hotel>
.....
Response.hotelInfo has #XmlElementWrapper(name="Hotelinfo") and #XmlElement(name="Hotelinfo"), which means that XML needs to be:
<EasytobookResponse>
<Response target="test" username="project121">
<Hotelinfo>
<Hotelinfo>
<Id>436924</Id>
To match your XML, the #XmlElement should be Hotel, not Hotelinfo.
Currently, the <Hotel> element is being skipped, and nothing is assigned to the Response.hotelInfo list, so response.getResponse().getHotelInfo().get(0) fails.
Next time, please show the line that gives the exception. Makes it SO much easier for us to help you.
I am trying to parse the XML response to an object but it throws exception.
The link of response is this:
<response>
<meta>
<per_page>10</per_page>
<total>20</total>
<geolocation>None</geolocation>
<took>8</took>
<page>1</page>
</meta>
<events>
<event>
...
</event>
<event>
...
</event>
....
</events>
</response>
Code
queryString = queryString.replaceAll(" ", "%20");
try {
URL page = new URL(queryString);
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader(conn.getInputStream(),Charset.forName("UTF-8"));
this.response = (Response) JAXB.unmarshal(in, Response.class);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
Exception
javax.xml.bind.DataBindingException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 40
counts of IllegalAnnotationExceptions
Class has two properties of the same name "events"
this problem is related to the following location:
....
Object classes
#XmlRootElement(name = "Response")
public class Response {
#XmlElement(name="per_page")
private int per_page;
#XmlElement(name="total")
private int total;
#XmlElement(name="geolocation")
private String geolocation;
#XmlElement(name="took")
private int took;
#XmlElement(name="page")
private int page;
#XmlElement(name="events")
private List<Event> events = null;
**getters and setters**
Objects
#XmlRootElement(name="event")
public class Event {
#XmlElement(name = "links")
private String link;
#XmlElement(name = "id")
private int id;
#XmlElement(name = "stats")
private Stats stats;
#XmlElement(name = "title")
private String title;
#XmlElement(name = "announce_date")
private String announce_date;
#XmlElement(name = "score")
private float score;
#XmlElement(name = "date_tbd")
private boolean date_tbd;
#XmlElement(name = "type")
private String type;
#XmlElement(name = "datetime_local")
private String datetime_local;
#XmlElement(name = "visible_until_utc")
private String visible_util_utc;
#XmlElement(name = "time_tbd")
private boolean time_tbd;
#XmlElement(name = "taxonomies")
private List<Taxonomie> taxonomies;
#XmlElement(name = "performers")
private List<Performer> performers;
#XmlElement(name = "url")
private String url;
#XmlElement(name = "created_at")
private String created_at;
#XmlElement(name = "venue")
private Venue venue;
#XmlElement(name = "short_title")
private String short_title;
#XmlElement(name = "datetime_utc")
private String datetime_utc;
#XmlElement(name = "datetime_tbd")
private boolean datetime_tbd;
**getters and setters**
By default JAXB implementations treat public fields and properties as mapped. When you annotate a non-public field it also becomes mapped. Then if you have a mapped field an property with the same name you will get this exception.
When you annotate fields you need to annotate your class with #XmlAccessorType(XmlAccessType.FIELD).
http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
Note:
You are currently adding more annotations on your model than you need to. Since JAXB is configuration by exception you only need to add annotations where you want the XML representation to differ from the default.
http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html