I could send a request and receive the response but I can not parse the response. It returns the following error:
Local Name:Body
error is here
java.lang.NullPointerException
at com.ticketmaster.ticketmaster.TicketMaster.Search(TicketMaster.java:119)
at com.ticketmaster.ticketmaster.App.main(App.java:12)
Code
SOAPMessage response
= connection.call(message, endpoint);
connection.close();
SOAPMessage sm = response;
SOAPBody sb = response.getSOAPBody();
System.err.println("Node Name:" + sb.getNodeName()); //return nothing
System.err.println("Local Name:" + sb.getLocalName()); //return Local Name:Body
DOMSource source = new DOMSource(sb);
results = (FindEventsResponse) JAXB.unmarshal(source, FindEventsResponse.class);
System.err.println("Results size: " + this.results.returnTag.results.item.get(0).getName());
} catch (Exception ex) {
System.err.println("error is here");
ex.printStackTrace();
}
Response:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://ticketmaster.productserve.com/v2/soap.php"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:findEventsResponse>
<return xsi:type="ns1:Response">
<details xsi:type="ns1:Details">
<totalResults xsi:type="xsd:int">20662</totalResults>
<totalPages xsi:type="xsd:int">414</totalPages>
<currentPage xsi:type="xsd:int">1</currentPage>
<resultsPerPage xsi:type="xsd:int">50</resultsPerPage>
</details>
<results SOAP-ENC:arrayType="ns1:Event[50]" xsi:type="ns1:ArrayOfEvent">
<item xsi:type="ns1:Event">
<eventId xsi:type="xsd:int">1516682</eventId>
<ticketmasterEventId xsi:type="xsd:string">18004C6E8D7218A8</ticketmasterEventId>
<status xsi:type="xsd:string">onSale</status>
<name xsi:type="xsd:string">The Art of the Brick</name>
<url xsi:type="xsd:string">http://www.ticketmaster.ie/event/18004C6E8D7218A8?camefrom=CFC_UK_BUYAT&brand=[=BRAND=]</url>
<eventDate xsi:type="xsd:string">2014-05-23 10:00:00</eventDate>
<onSaleDate xsi:type="xsd:string">0000-00-00 00:00:00</onSaleDate>
<preSaleDate xsi:type="xsd:string">0000-00-00 00:00:00</preSaleDate>
<category xsi:type="xsd:string">Exhibitions</category>
<categoryId xsi:type="xsd:int">754</categoryId>
<parentCategory xsi:type="xsd:string">Family & Attractions</parentCategory>
<parentCategoryId xsi:type="xsd:int">10003</parentCategoryId>
<minPrice xsi:type="xsd:float">17</minPrice>
<maxPrice xsi:type="xsd:float">17</maxPrice>
<artists SOAP-ENC:arrayType="ns1:Artist[1]" xsi:type="ns1:ArrayOfArtist">
<item xsi:type="ns1:Artist">
<artistId xsi:type="xsd:int">1806028</artistId>
<ticketmasterArtistId xsi:type="xsd:int">1663495</ticketmasterArtistId>
<name xsi:type="xsd:string">The Art of the Brick</name>
<url xsi:type="xsd:string">http://www.ticketmaster.co.uk/The-Art-of-the-Brick-tickets/artist/1663495?camefrom=CFC_UK_BUYAT&brand=[=BRAND=]</url>
<imageUrl xsi:type="xsd:string">http://media.ticketmaster.com/tm/en-us/tmimages/TM_GenCatImgs_Generic_BW.jpg</imageUrl>
<category xsi:type="xsd:string">Miscellaneous</category>
<categoryId xsi:type="xsd:int">0</categoryId>
<parentCategory xsi:type="xsd:string">Miscellaneous</parentCategory>
<parentCategoryId xsi:type="xsd:int">10005</parentCategoryId>
</item>
</artists>
<venue xsi:type="ns1:Venue">
<venueId xsi:type="xsd:int">3331</venueId>
<ticketmasterVenueId xsi:type="xsd:int">198292</ticketmasterVenueId>
<name xsi:type="xsd:string">Ambassador Theatre</name>
<street xsi:type="xsd:string">Oconnell Street</street>
<city xsi:type="xsd:string">Dublin</city>
<country xsi:type="xsd:string">United Kingdom</country>
<postcode xsi:type="xsd:string">Dublin 1</postcode>
<url xsi:type="xsd:string">http://www.ticketmaster.ie/Ambassador-Theatre-tickets-Dublin/venue/198292?camefrom=CFC_UK_BUYAT&brand=</url>
<imageUrl xsi:type="xsd:string">http://media.ticketmaster.co.uk/tmimages/TM_GenVenueImg_BW.jpg</imageUrl>
<state xsi:type="xsd:string"></state>
</venue>
</item>
<item xsi:type="ns1:Event">
....
Model Classes
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class FindEventsResponse {
#XmlElement(name = "return")
Return returnTag;
public FindEventsResponse() {
this.returnTag = new Return();
}
getter and setter
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Return {
#XmlElement(name = "details")
Details details;
#XmlElement(name = "results")
Results results;
public Return(Details details, Results results) {
this.details = new Details();
this.results = new Results();
}
getters and setters
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Details {
#XmlElement(name = "totalResults")
int totalResults;
#XmlElement(name = "totalPages")
int totalPages;
#XmlElement(name = "currentPage")
int currentPage;
#XmlElement(name = "resultPerPage")
int resultsPerPage;
getters and setters
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Results {
#XmlElement(name = "item")
List<Item> item;
public Results() {
this.item = new ArrayList();
}
getter and setter
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Item {
#XmlElement(name = "eventId")
int eventId;
#XmlElement(name = "ticketmasterEventId")
String ticketmasterEventId;
#XmlElement(name = "status")
String status;
#XmlElement(name = "name")
String name;
#XmlElement(name = "url")
String url;
#XmlElement(name = "eventDate")
String eventDate;
#XmlElement(name = "onSaleDate")
String onSaleDate;
#XmlElement(name = "preSaleDate")
String preSaleDate;
#XmlElement(name = "category")
String category;
#XmlElement(name = "categoryId")
int categoryId;
#XmlElement(name = "parentCategory")
String parentCategory;
#XmlElement(name = "parentCategoryId")
int parentCategoryId;
#XmlElement(name = "minPrice")
int minPrice;
#XmlElement(name = "maxPrice")
int maxPrice;
#XmlElement(name = "artists")
private Artists artist;
#XmlElement(name = "venue")
private Venue venue;
public Item() {
this.artist = new Artists();
this.venue = new Venue();
}
getters and setters
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Artists {
#XmlElement(name = "artists")
private ArtistItem item;
public Artists() {
this.item = new ArtistItem();
}
getter and setter
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class ArtistItem {
#XmlElement(name = "artistId")
int artistId;
#XmlElement(name = "ticketmasterArtistsId")
int ticketmasterArtistId;
#XmlElement(name = "name")
String name;
#XmlElement(name = "url")
String url;
#XmlElement(name = "imageUrl")
String imageUrl;
#XmlElement(name = "category")
String category;
#XmlElement(name = "categoryId")
int categoryId;
#XmlElement(name = "parentCategory")
String parentCategory;
#XmlElement(name = "parentCategoryId")
int parentCategoryId;
getters and setters
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Venue {
#XmlElement(name = "venueId")
int venueId;
#XmlElement(name = "ticketmasterVenueId")
int ticketmasterVenueId;
#XmlElement(name = "name")
String name;
#XmlElement(name = "street")
String street;
#XmlElement(name = "city")
String city;
#XmlElement(name = "country")
String country;
#XmlElement(name = "postcode")
String postcode;
#XmlElement(name = "url")
String url;
#XmlElement(name = "imageUrl")
String imageUrl;
#XmlElement(name = "state")
String state;
getters and setters
}
Based on one of the following answers, I marshalled the result and it shows a wrong response.
package-info.java
#XmlSchema(
namespace = "http://ticketmaster.productserve.com/v2/soap.php",
elementFormDefault = XmlNsForm.UNQUALIFIED)
package com.ticketmaster.ticketmaster;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
Code
SOAPBody sb = response.getSOAPBody();
System.err.println(">>"+ sb.getFirstChild().getNodeName());
Iterator itr = sb.getChildElements();
while(itr.hasNext()){
Object element = itr.next();
System.err.println(element + " ");
}
Document d = sb.extractContentAsDocument();
System.err.println("result of d:"+d.getTextContent());
DOMSource source = new DOMSource(d);
results = (FindEventsResponse) JAXB.unmarshal(source, FindEventsResponse.class);
System.err.println("results>"+results.getReturnTag().getResults().getItem().get(0).getName());
Error is
.....
><city xsi:type="xsd:string">London</city><country xsi:type="xsd:string">United Kingdom</country><postcode xsi:type="xsd:string">SE1 8XX</postcode><url xsi:type="xsd:string">http://www.ticketmaster.co.uk/The-London-Wonderground-tickets-London/venue/253993?camefrom=CFC_UK_BUYAT&brand=</url><imageUrl xsi:type="xsd:string">http://media.ticketmaster.co.uk/tmimages/TM_GenVenueImg_BW.jpg</imageUrl><state xsi:type="xsd:string"></state></venue></item></results></return></ns1:findEventsResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
>>ns1:findEventsResponse
[ns1:findEventsResponse: null]
result of d:null
error is here
java.lang.IllegalArgumentException: prefix xsd is not bound to a namespace
at com.sun.xml.internal.bind.DatatypeConverterImpl._parseQName(DatatypeConverterImpl.java:346)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.LeafPropertyXsiLoader.selectLoader(LeafPropertyXsiLoader.java:75)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.LeafPropertyXsiLoader.startElement(LeafPropertyXsiLoader.java:58)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:486)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:465)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:135)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:229)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:266)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:235)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:266)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:235)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:266)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:235)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:266)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:235)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:112)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:95)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:312)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:288)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:238)
at javax.xml.bind.JAXB.unmarshal(JAXB.java:259)
at com.ticketmaster.ticketmaster.TicketMaster.Search(TicketMaster.java:132)
at com.ticketmaster.ticketmaster.App.main(App.java:12)
Ensure You Are Unmarshalling the Correct Thing
You need to unmarshal the content held onto by SOAP body, not the entire SOAP message. Below is what the code might look like:
SOAPMessage sm = response;
SOAPBody sb = response.getSOAPBody();
Document d = sb.extractContentAsDocument();
DOMSource source = new DOMSource(d);
results = (FindEventsResponse) JAXB.unmarshal(source, FindEventsResponse.class);
The result of sb.extractContentAsDocument is going to be a DOM that is equivalent to the following:
<?xml version="1.0" encoding="UTF-8"?>
<ns1:findEventsResponse xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://ticketmaster.productserve.com/v2/soap.php"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<return xsi:type="ns1:Response">
<details xsi:type="ns1:Details">
<totalResults xsi:type="xsd:int">20662</totalResults>
<totalPages xsi:type="xsd:int">414</totalPages>
<currentPage xsi:type="xsd:int">1</currentPage>
<resultsPerPage xsi:type="xsd:int">50</resultsPerPage>
</details>
<results SOAP-ENC:arrayType="ns1:Event[50]" xsi:type="ns1:ArrayOfEvent">
<item xsi:type="ns1:Event">
<eventId xsi:type="xsd:int">1516682</eventId>
<ticketmasterEventId xsi:type="xsd:string">18004C6E8D7218A8</ticketmasterEventId>
<status xsi:type="xsd:string">onSale</status>
<name xsi:type="xsd:string">The Art of the Brick</name>
<url xsi:type="xsd:string">http://www.ticketmaster.ie/event/18004C6E8D7218A8?camefrom=CFC_UK_BUYAT&brand=[=BRAND=]</url>
<eventDate xsi:type="xsd:string">2014-05-23 10:00:00</eventDate>
<onSaleDate xsi:type="xsd:string">0000-00-00 00:00:00</onSaleDate>
<preSaleDate xsi:type="xsd:string">0000-00-00 00:00:00</preSaleDate>
<category xsi:type="xsd:string">Exhibitions</category>
<categoryId xsi:type="xsd:int">754</categoryId>
<parentCategory xsi:type="xsd:string">Family & Attractions</parentCategory>
<parentCategoryId xsi:type="xsd:int">10003</parentCategoryId>
<minPrice xsi:type="xsd:float">17</minPrice>
<maxPrice xsi:type="xsd:float">17</maxPrice>
<artists SOAP-ENC:arrayType="ns1:Artist[1]" xsi:type="ns1:ArrayOfArtist">
<item xsi:type="ns1:Artist">
<artistId xsi:type="xsd:int">1806028</artistId>
<ticketmasterArtistId xsi:type="xsd:int">1663495</ticketmasterArtistId>
<name xsi:type="xsd:string">The Art of the Brick</name>
<url xsi:type="xsd:string">http://www.ticketmaster.co.uk/The-Art-of-the-Brick-tickets/artist/1663495?camefrom=CFC_UK_BUYAT&brand=[=BRAND=]</url>
<imageUrl xsi:type="xsd:string">http://media.ticketmaster.com/tm/en-us/tmimages/TM_GenCatImgs_Generic_BW.jpg</imageUrl>
<category xsi:type="xsd:string">Miscellaneous</category>
<categoryId xsi:type="xsd:int">0</categoryId>
<parentCategory xsi:type="xsd:string">Miscellaneous</parentCategory>
<parentCategoryId xsi:type="xsd:int">10005</parentCategoryId>
</item>
</artists>
<venue xsi:type="ns1:Venue">
<venueId xsi:type="xsd:int">3331</venueId>
<ticketmasterVenueId xsi:type="xsd:int">198292</ticketmasterVenueId>
<name xsi:type="xsd:string">Ambassador Theatre</name>
<street xsi:type="xsd:string">Oconnell Street</street>
<city xsi:type="xsd:string">Dublin</city>
<country xsi:type="xsd:string">United Kingdom</country>
<postcode xsi:type="xsd:string">Dublin 1</postcode>
<url xsi:type="xsd:string">http://www.ticketmaster.ie/Ambassador-Theatre-tickets-Dublin/venue/198292?camefrom=CFC_UK_BUYAT&brand=</url>
<imageUrl xsi:type="xsd:string">http://media.ticketmaster.co.uk/tmimages/TM_GenVenueImg_BW.jpg</imageUrl>
<state xsi:type="xsd:string"></state>
</venue>
</item>
<item xsi:type="ns1:Event"></item>
</results>
</return>
</ns1:findEventsResponse>
UPDATE
Based on the new exception you are getting:
java.lang.IllegalArgumentException: prefix xsd is not bound to a namespace
at com.sun.xml.internal.bind.DatatypeConverterImpl._parseQName(DatatypeConverterImpl.java:346)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.LeafPropertyXsiLoader.selectLoader(LeafPropertyXsiLoader.java:75)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.LeafPropertyXsiLoader.startElement(LeafPropertyXsiLoader.java:58)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:486)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:465)
It appears as though sb.extractContentAsDocument(); is not bringing along the xmlns:xsd declaration from the SOAP message. Instead you can change the code to do the following:
SOAPMessage sm = response;
SOAPBody sb = response.getSOAPBody();
DOMSource source = new DOMSource(sb.getFirstChild());
results = (FindEventsResponse) JAXB.unmarshal(source, FindEventsResponse.class);
Ensure the Namespace Qualification is Mapped Correctly
Having the following tells JAXB that everything mapped to an XML element without an explicitly specified namespace should belong in the http://ticketmaster.productserve.com/v2/soap.php namespace.
#XmlSchema(
namespace = "http://ticketmaster.productserve.com/v2/soap.php",
elementFormDefault = XmlNsForm.QUALIFIED)
package com.ticketmaster.ticketmaster;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
In your XML only the findEventsResponse element is namespace qualified. This means your annotation should be the following instead (note change from QUALIFIED to UNQUALIFIED):
#XmlSchema(
namespace = "http://ticketmaster.productserve.com/v2/soap.php",
elementFormDefault = XmlNsForm.UNQUALIFIED)
package com.ticketmaster.ticketmaster;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
Demo Code
Using the above XML as input.xml I was able to unmarshal and marshal the model as you have defined it in your question with the #XmlSchema fix mentioned above.
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(FindEventsResponse.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource("src/forum23806625/input.xml");
JAXBElement<FindEventsResponse> response = unmarshaller.unmarshal(xml, FindEventsResponse.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(response, System.out);
}
}
Related
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:cs=\"urn:CardServices\" xmlns:ebppif1=\"urn:PaymentServer\" xmlns:el=\"urn:ExtListsServices\" xmlns:iiacs=\"urn:IIACardServices\" xmlns:lm=\"urn:Limits\">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring></faultstring>
<detail>
<ebppif1:PaymentServerException>
<provider>RSW</provider>
<error>129</error>
<description>201433</description>
<screen>RSW129</screen>
</ebppif1:PaymentServerException>
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
How to create java object using #XmlRootElement,#XmlElement.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "Fault", namespace = "http://schemas.xmlsoap.org/soap/envelope/")
#Data
public class FaultDto {
#XmlElement(name = "faultcode")
private String faultCode;
#XmlElement(name = "detail")
private DetailDto detail;
}
#XmlRootElement(name = "detail")
#XmlAccessorType(XmlAccessType.FIELD)
public class DetailDto {
#XmlElement(name = "PaymentServerException")
private PaymentExcepDto excepDto;
}
#XmlRootElement(name = "PaymentServerException")
#XmlAccessorType(XmlAccessType.FIELD)
public class PaymentExcepDto {
#XmlElement(name = "provider")
protected String provider;
#XmlElement(name = "error")
protected String error;
//others
}
I am getting this result : FaultDto(faultCode=SOAP-ENV:Client, detail=DetailDto(excepDto=null))
How to catch PaymentServerException ?
I can’t understand what I am doing wrong.I need to unmarshal xml file that looks like this:
<ApplicationMetadata xmlns="http://www.sas.com/xml/schema/namespace/ApplicationMetadata-9.4">
<Role Name="name1" Desc="desc1 " DisplayName="disp1 ">
<Members/>
<ContributingRoles/>
<Capabilities>
<Capability CapabilityId="1"/>
<Capability CapabilityId="2"/>
<Capability CapabilityId="3"/>
</Capabilities>
</Role>
<Role Name="name2" Desc="desc2" DisplayName="disp2">
<Members>
<UserGroup Name="userGoup"/>
</Members>
<ContributingRoles/>
<Capabilities>
<Capability CapabilityId="1"/>
<Capability CapabilityId="2"/>
</Capabilities>
</Role>
</ApplicationMetadata>
I have next classes:
#XmlRootElement(name = "ApplicationMetadata", namespace = "http://www.sas.com/xml/schema/namespace/ApplicationMetadata-9.4")
#XmlAccessorType(XmlAccessType.FIELD)
public class ApplicationMetaData {
#XmlElement(name = "Role")
private List<Role> roles;
getters and setters
}
#XmlRootElement(name = "Role")
#XmlAccessorType(XmlAccessType.FIELD)
public class Role {
#XmlAttribute(name = "Name")
private String name;
#XmlAttribute(name = "Desc")
private String desc;
#XmlAttribute(name = "DisplayName")
private String displayName;
#XmlElementWrapper(name = "ContributingRoles")
#XmlElement(name = "UserGroup")
private List<UserGroup> contributionRoles;
#XmlElementWrapper(name = "Members")
#XmlElement(name = "UserGroup")
private List<UserGroup> members;
#XmlElementWrapper(name = "Capabilities")
#XmlElement(name = "Capability")
private List<Capability> capabilities;
getters and setters
}
#XmlRootElement(name = "Capability")
#XmlAccessorType(XmlAccessType.FIELD)
public class Capability {
#XmlAttribute(name = "CapabilityId")
private String id;
getters and setters
}
#XmlRootElement (name = "UserGroup")
#XmlAccessorType(XmlAccessType.FIELD)
public class UserGroup {
#XmlAttribute(name = "Name")
private String name;
getters and setters
}
My code for unmarshaling is:
File file = new File(fileName);
ApplicationMetaData appMetaData = (ApplicationMetaData)
WorkWithXml.unmarshalXml(file, ApplicationMetaData.class);
public static Object unmarshalXml(File file, Class unmarshallerClass) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(unmarshallerClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return unmarshaller.unmarshal(file);
} catch (JAXBException e) {
LOG.error("", e);
throw new AutotestError(e);
}
}
As result I have appMetaData object with all roles from file. Roles has attributes, but all lists inside roles are empty. Not null, but empty. Where I have a mistake?
P.S. It is all about Java code :)
I have done it :)
Instead
#XmlElementWrapper(name = "Capabilities")
#XmlElement(name = "Capability")
private List<Capability> capabilities;
in Role class I have used
#XmlElement (name = "Capabilities")
Capabilities capabilities;
And here Capabilities class
#XmlRootElement(name = "Capabilities")
#XmlAccessorType(XmlAccessType.FIELD)
public class Capabilities {
#XmlElement(name = "Capability")
private List<Capability> capability;
public List<Capability> getCapability() {
return capability;
}
public void setCapability(List<Capability> capability) {
this.capability = capability;
}
}
I have the following objects
Film
#Entity
#Table(name="film")
#XmlRootElement(name = "film")
public class Film implements Serializable {
#Id
#Column(name="id")
private String fbId;
#Column(name="title")
private String title;
#ManyToMany
#JoinTable(
name="direction",
joinColumns={#JoinColumn(name="film", referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="person", referencedColumnName="id")})
private Collection<Person> directors;
#OneToMany(cascade={CascadeType.ALL}, mappedBy="film")
#MapKey(name="character")
private Map<String, Performance> performances;
//GETTERS
#XmlAttribute(name = "fbId")
public String getFreebaseId() {
return this.fbId;
}
#XmlElementRefs({
#XmlElementRef(name="director", type=Person.class)
})
public Collection<Person> getDirectors() {
return this.directors;
}
#XmlAnyElement(lax=true)
public Collection<Performance> getPerformances() {
ArrayList performancesArray = new ArrayList<Performance>();
for (Map.Entry<String, Performance> entry : this.performances.entrySet()) {
Performance value = entry.getValue();
performancesArray.add(value);
}
return performancesArray;
}
}
Person
#Entity
#Table(name="person")
public class Person implements Serializable {
#Id
#Column(name="id")
private String fbId;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#OneToMany(cascade={CascadeType.ALL}, mappedBy="actor")
#XmlTransient
private Collection<Performance> performances;
//GETTERS
#XmlAttribute(name = "fbId")
public String getFreebaseId() {
return this.fbId;
}
#XmlElement(name = "firstName")
public String getFirstName() {
return this.firstName;
}
#XmlElement(name = "lastName")
public String getLastName() {
return this.lastName;
}
#XmlTransient
public Collection<Performance> getPerformances() {
return this.performances;
}
}
Each film has one (or many) directors and performances which are "Persons". I don't need a class for directors but I do for perfomances because they have more info.
Performance
#Entity
#Table(name="performance")
#XmlRootElement(name = "performace")
public class Performance implements Serializable {
#Id
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="film")
private Film film;
#Id
#Column(name="film_character")
private String character;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="actor")
private Person actor;
//TO STRING
public String toString() {
return this.actor.toString() + " - " + this.character;
}
//GETTERS
#XmlTransient
public Film getFilm() {
return this.film;
}
#XmlElementRefs({
#XmlElementRef(name = "firstName", type = Person.class),
#XmlElementRef(name = "lastName", type = Person.class)
})
public Person getActor() {
return this.actor;
}
#XmlElement(name = "character")
public String getCharacter() {
return this.character;
}
}
When I run this through JAXB I get this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<film fbId="1">
<description>Nice film</description>
<person fbId="1">
<firstName>Quentin</firstName>
<lastName>Tarantino</lastName>
</person>
<performace>
<person fbId="4">
<firstName>Steve</firstName>
<lastName>Buscemi</lastName>
</person>
<character>Billy</character>
</performace>
<performace>
<person fbId="2">
<firstName>Jhon</firstName>
<lastName>Travolta</lastName>
</person>
<character>Vincent</character>
</performace>
<performace>
<person fbId="3">
<firstName>Samuel</firstName>
<lastName>L Jackson</lastName>
</person>
<character>Jules</character>
</performace>
<performace>
<person fbId="1">
<firstName>Quentin</firstName>
<lastName>Tarantino</lastName>
</person>
<character>Jimmie</character>
</performace>
<title>Pulp Fiction</title>
</film>
Is there a way to change the name of the "person"? To get something like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<film fbId="1">
<description>Nice film</description>
<director fbId="1">
<firstName>Quentin</firstName>
<lastName>Tarantino</lastName>
</director>
<performace fbId="4">
<firstName>Steve</firstName>
<lastName>Buscemi</lastName>
<character>Billy</character>
</performace>
<performace fbId="2">
<firstName>Jhon</firstName>
<lastName>Travolta</lastName>
<character>Vincent</character>
</performace>
<performace fbId="3">
<firstName>Samuel</firstName>
<lastName>L Jackson</lastName>
<character>Jules</character>
</performace>
<performace fbId="1">
<firstName>Quentin</firstName>
<lastName>Tarantino</lastName>
<character>Jimmie</character>
</performace>
<title>Pulp Fiction</title>
</film>
Options:
Make Director extends Person with its own #XmlRootElement
Use JAXBElement<? extends Person> instead of Person
The problem is, #XmlElementRef.name does not work for #XmlRootElement, read here:
If type() is JAXBElement.class , then namespace() and name() point to
a factory method with XmlElementDecl. The XML element name is the
element name from the factory method's XmlElementDecl annotation or if
an element from its substitution group (of which it is a head element)
has been substituted in the XML document, then the element name is
from the XmlElementDecl on the substituted element.
If type() is not JAXBElement.class, then the XML element name is the
XML element name statically associated with the type using the
annotation XmlRootElement on the type. If the type is not annotated
with an XmlElementDecl, then it is an error.
If type() is not JAXBElement.class, then this value must be "".
By the way
#XmlElementRefs({
#XmlElementRef(name = "firstName", type = Person.class),
#XmlElementRef(name = "lastName", type = Person.class)
})
does not seem valid to me. #XmlElementRef are not supposed to map properties of the target class.
I am trying to parse a SOAP response. I can show the full response using following line.
System.out.println("Response: " + out.toString());
However when I parse the response and marshall the parsed response, it shows a wrong response.
package-info.java
#XmlSchema(
namespace = "http://v3.hotel.wsapi.ean.com/",
elementFormDefault = XmlNsForm.QUALIFIED)
package com.ean;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
My Code
#XmlRootElement(name="getListResponse")
#XmlAccessorType(XmlAccessType.FIELD)
public class GetListResponse {
#XmlElement(name="HotelListResponse")
private HotelListResponse hotelListResponse;
public GetListResponse() {
this.hotelListResponse = new HotelListResponse();
}
…getter and setter
}
#XmlRootElement(name ="HotelListResponse")
#XmlAccessorType(XmlAccessType.FIELD)
public class HotelListResponse {
#XmlElement(name = "customerSessionId")
String customerSessionId;
#XmlElement(name = "numberOfRoomsRequested")
int numberOfRoomsRequested;
#XmlElement(name = "moreResultsAvailable")
boolean moreResultsAvailable;
#XmlElement(name = "cacheKey")
String cacheKey;
#XmlElement(name="cacheLocation")
String cachLocation;
#XmlElement(name = "HotelList")
HotelList hotelList;
public HotelListResponse() {
this.hotelList = new HotelList();
}
… getters and setters…
}
#XmlRootElement(name ="HotelList")
#XmlAccessorType(XmlAccessType.FIELD)
public class HotelList {
#XmlAttribute(name = "size")
int size;
#XmlAttribute(name = "activePropertyCount")
int activePropertyCount;
#XmlElement(name = "HotelSummary")
List <HotelSummary> hotelSummaries;
public HotelList() {
this.hotelSummaries = new ArrayList();
}
… getters and setters…
}
#XmlRootElement(name = "HotelSummary")
#XmlAccessorType(XmlAccessType.FIELD)
public class HotelSummary {
#XmlAttribute(name = "order")
int order;
#XmlElement(name = "hotelId")
int hotelId;
#XmlElement(name = "name")
String name;
#XmlElement(name = "address1")
String address1;
#XmlElement(name = "city")
String city;
#XmlElement(name = "stateProvinceCode")
String stateProvinceCode;
#XmlElement(name = "postalCode")
int postalCode;
#XmlElement(name = "countryCode")
String countryCode;
#XmlElement(name = "airportCode")
String airportCode;
#XmlElement(name = "supplierType")
String supplierType;
#XmlElement(name = "propertyCategory")
int propertyCategory;
#XmlElement(name = "hotelRating")
float hotelRating;
#XmlElement(name = "confidenceRating")
int confidenceRating;
#XmlElement(name = "amenityMask")
int amenityMask;
#XmlElement(name = "tripAdvisorRating")
float tripAdvisorRating;
#XmlElement(name = "locationDescription")
String locationDescription;
#XmlElement(name = "shortDescription")
String shortDescriptionl; //change amp to &
#XmlElement(name = "highRate")
String highRate;
#XmlElement(name = "lowRate")
float lowRate;
#XmlElement(name = "rateCurrencyCode")
String rateCurrencyCode;
#XmlElement(name = "latitude")
float latitude;
#XmlElement(name = "longitude")
float longitude;
#XmlElement(name = "proximityDistance")
float proximityDistance;
#XmlElement(name = "proximityUnit")
String proximityUnit;
#XmlElement(name = "hotelInDestination")
boolean hotelInDestination;
#XmlElement(name = "thumbNailUrl")
String thumbNailUrl;
#XmlElement(name = "deepLink")
String deepLink;
#XmlElement(name = "RoomRateDetailsList")
RoomRateDetailsList roomRateDetailsList;
public HotelSummary() {
this.roomRateDetailsList = new RoomRateDetailsList();
}
… getters and setters…
}
#XmlRootElement(name = "RoomRateDetailsList")
#XmlAccessorType(XmlAccessType.FIELD)
public class RoomRateDetailsList {
#XmlElement(name="RoomRateDetails")
List<RoomRateDetails> roomRateDetails;
public RoomRateDetailsList() {
this.roomRateDetails = new ArrayList();
}
.. getter and setter..
}
#XmlRootElement(name = "RoomRateDetails")
#XmlAccessorType(XmlAccessType.FIELD)
public class RoomRateDetails {
#XmlElement(name="roomTypeCode")
int roomTypeCode;
#XmlElement(name="rateCode")
int rateCode;
#XmlElement(name="maxRoomOccupancy")
int maxRoomOccupancy;
#XmlElement(name="quotedRoomOccupancy")
int quotedRoomOccupancy;
#XmlElement(name="minGuestAge")
int minGuestAge;
#XmlElement(name="roomDescription")
String roomDescription;
#XmlElement(name="promoId")
int promoId;
#XmlElement(name="promoDescription")
String promoDescription;
#XmlElement(name="currentAllotment")
int currentAllotment;
#XmlElement(name="propertyAvailable")
boolean propertyAvailable;
#XmlElement(name="propertyRestricted")
boolean propertyRestricted;
#XmlElement(name="expediaPropertyId")
int expediaPropertyId;
#XmlElement(name="rateKey")
String rateKey;
#XmlElement(name="RateInfo")
RateInfo rateInfo;
#XmlElement(name="ValueAdds")
ValueAdds valueAdds;
public RoomRateDetails() {
this.rateInfo = new RateInfo();
this.valueAdds = new ValueAdds();
}
… getters and setters…
}
#XmlRootElement(name = "RoomInfo")
#XmlAccessorType(XmlAccessType.FIELD)
public class RateInfo {
#XmlAttribute(name="priceBreakdown")
boolean priceBreakdown;
#XmlAttribute(name="promo")
boolean promo;
#XmlAttribute(name="rateChange")
boolean rateChange;
#XmlElement(name="ChargeableRateInfo")
ChargeableRateInfo chargeableRateInfo;
public RateInfo() {
this.chargeableRateInfo = new ChargeableRateInfo();
}
.. getters and setters…
}
#XmlRootElement(name = "ChargeableRateInfo")
#XmlAccessorType(XmlAccessType.FIELD)
public class ChargeableRateInfo {
#XmlAttribute(name="averageBaseRate")
float averageBaseRate;
#XmlAttribute(name="averageRate")
float averageRate;
#XmlAttribute(name="commissionableUsdTotal")
float commissionableUsdTotal;
#XmlAttribute(name="currencyCode")
String currencyCode;
#XmlAttribute(name="maxNightlyRate")
float maxNightlyRate;
#XmlAttribute(name="nightlyRateTotal")
float nightlyRateTotal;
#XmlAttribute(name="total")
float total;
#XmlElement(name="NightlyRatesPerRoom")
NightlyRatesPerRoom nightlyRatesPerRoom;
public ChargeableRateInfo() {
this.nightlyRatesPerRoom = new NightlyRatesPerRoom();
}
… getters and setters…
}
#XmlRootElement(name = "NightlyRatesPerRoom")
#XmlAccessorType(XmlAccessType.FIELD)
public class NightlyRatesPerRoom {
#XmlAttribute(name="size")
int size;
#XmlElement(name="NightlyRate")
NightlyRate nightlyRate;
public NightlyRatesPerRoom() {
this.nightlyRate = new NightlyRate();
}
… getters and setters…
}
#XmlRootElement(name = "NightlyRate")
#XmlAccessorType(XmlAccessType.FIELD)
public class NightlyRate {
#XmlAttribute(name="baseRate")
float baseRate;
#XmlAttribute(name="rate")
float rate;
#XmlAttribute(name="promo")
float promo;
public NightlyRate() {
}
… getters and setters…
}
#XmlRootElement(name = "ValueAdds")
#XmlAccessorType(XmlAccessType.FIELD)
public class ValueAdds {
#XmlAttribute(name="size")
private int size;
#XmlElement(name="ValueAdd")
private List<ValueAdd> valueAdd;
public ValueAdds() {
this.valueAdd = new ArrayList();
}
… getters and setters…
}
#XmlRootElement(name = "ValueAdd")
#XmlAccessorType(XmlAccessType.FIELD)
public class ValueAdd {
#XmlAttribute(name="id")
private int id;
#XmlElement(name="description")
private String description;
public ValueAdd() {
}
… getters and setters…
}
Code
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPHeader header = message.getSOAPHeader();
header.detachNode();
SOAPBody body = message.getSOAPBody();
Name bodyName;
bodyName = soapFactory.createName("getList",
"v3", "http://v3.hotel.wsapi.ean.com/");
SOAPBodyElement getList
= body.addBodyElement(bodyName);
Name childName = soapFactory.createName("HotelListRequest");
SOAPElement HotelListRequest = getList.addChildElement(childName);
……Here, I add child nodes of the request…...
message.writeTo(System.out); //show message details
URL endpoint = new URL("http://dev.api.ean.com/ean-services/ws/hotel/v3");
SOAPMessage response = connection.call(message, endpoint);
connection.close();
SOAPMessage sm = response;
System.err.println("Response:");
ByteArrayOutputStream out = new ByteArrayOutputStream();
sm.writeTo(out);
System.err.println(">>>" + out.toString());
System.err.println(">>>>>>>>>>>parse:");
SOAPBody sb = response.getSOAPBody();
DOMSource source = new DOMSource(sb);
HotelListResponse results = new HotelListResponse();
results = (HotelListResponse) JAXB.unmarshal(source, HotelListResponse.class);
JAXBContext context = JAXBContext.newInstance(HotelListResponse.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
System.err.println("Response *******");
m.marshal(results, System.out);
System.err.println("116872:" + results.getHotelList().getHotelSummaries().get(0).getHotelId());
} catch (Exception ex) {
ex.printStackTrace();
}
Actual Respose
Response:
Response:>>><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:getListResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/">
<HotelListResponse>
<customerSessionId>0ABAAA95-28B2-5914-7952-0331AC9069EA</customerSessionId>
<numberOfRoomsRequested>1</numberOfRoomsRequested>
<moreResultsAvailable>true</moreResultsAvailable>
<cacheKey>-41118b29:146950321ac:-69e1</cacheKey>
<cacheLocation>10.176.160.143:7300</cacheLocation>
<HotelList size="25" activePropertyCount="119">
<HotelSummary order="0">
<hotelId>150241</hotelId>
<name>Rydges World Square</name>
<address1>389 Pitt Street</address1>
<city>Sydney</city>
<stateProvinceCode>NW</stateProvinceCode>
<postalCode>2000</postalCode>
<countryCode>AU</countryCode>
<airportCode>SYD</airportCode>
<supplierType>E</supplierType>
<propertyCategory>1</propertyCategory>
<hotelRating>4.5</hotelRating>
<confidenceRating>52</confidenceRating>
<amenityMask>1343491</amenityMask>
<tripAdvisorRating>3.5</tripAdvisorRating>
<locationDescription>Near Darling Harbour</locationDescription>
<shortDescription><p><b>Property Location</b> <br />With a stay at Rydges World Square, you'll be centrally located in Sydney, steps from World Square Shopping Centre and minutes from Capitol Theatre. This 4.5-star</shortDescription>
<highRate>218.64</highRate>
<lowRate>218.64</lowRate>
<rateCurrencyCode>USD</rateCurrencyCode>
<latitude>-33.8766</latitude>
<longitude>151.20752</longitude>
<proximityDistance>0.5492472</proximityDistance>
<proximityUnit>MI</proximityUnit>
<hotelInDestination>true</hotelInDestination>
<thumbNailUrl>/hotels/1000000/570000/565000/564969/564969_91_t.jpg</thumbNailUrl>
<deepLink>http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=150241&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=5&arrivalDay=18&departureMonth=5&departureDay=19&showInfo=true&locale=en_US&currencyCode=USD</deepLink>
<RoomRateDetailsList>
<RoomRateDetails>
<roomTypeCode>200156055</roomTypeCode>
<rateCode>202768754</rateCode>
<maxRoomOccupancy>2</maxRoomOccupancy>
<quotedRoomOccupancy>2</quotedRoomOccupancy>
<minGuestAge>0</minGuestAge>
<roomDescription>Special: Deluxe King - Check-In from 8:30pm</roomDescription>
<promoId>201528081</promoId>
<promoDescription>Sale! Save 25% on this Stay.</promoDescription>
<currentAllotment>10</currentAllotment>
<propertyAvailable>true</propertyAvailable>
<propertyRestricted>false</propertyRestricted>
<expediaPropertyId>564969</expediaPropertyId>
<rateKey>0ABAAA85-18B2-9914-6952-0351AC9069DF</rateKey>
<RateInfo priceBreakdown="true" promo="true" rateChange="false">
<ChargeableRateInfo averageBaseRate="218.64" averageRate="218.64" commissionableUsdTotal="218.64" currencyCode="USD" maxNightlyRate="218.64" nightlyRateTotal="218.64" total="218.64">
<NightlyRatesPerRoom size="1">
<NightlyRate baseRate="218.64" rate="218.64" promo="false"/>
</NightlyRatesPerRoom>
</ChargeableRateInfo>
</RateInfo>
<ValueAdds size="1">
<ValueAdd id="2048">
<description>Free Wireless Internet</description>
</ValueAdd>
</ValueAdds>
</RoomRateDetails>
<RoomRateDetails>
...
>>>>>>>>>>>parse:
Response *******
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<HotelListResponse xmlns="http://v3.hotel.wsapi.ean.com/">
<numberOfRoomsRequested>0</numberOfRoomsRequested>
<moreResultsAvailable>false</moreResultsAvailable>
<HotelList size="0" activePropertyCount="0"/>
</HotelListResponse>
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at com.expedia.Engine.retrieveHotels(Engine.java:135)
at com.hotelsdotcom.App.main(App.java:17)
How to Fix Things
Unmarshal at the Right Level
Currently you are unmarshalling the XML node that corresponds to the soap:Body element, instead you need to navigate down to the HotelListResponse element and unmarshal that.
You could try the following:
DOMSource source = new DOMSource(sb.getFirstChild().getFirstChild());
Watch your Namespace Qualification
In the XML that you have marshalled all the elements appear qualified with the http://v3.hotel.wsapi.ean.com/, the document that you are trying to unmarshal doesn't have this namespace qualification so you should remove the #XmlSchema annotation from the package-info class.
Use Unmarshaller instead of JAXB.unmarshal
Instead of doing the following:
results = (HotelListResponse) JAXB.unmarshal(source, HotelListResponse.class);
I would recommend doing:
JAXBContext jc = JAXBContext.newInstance(HotelListResponse.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
results = unmarshaller.unmarshal(source, HotelListResponse.class).getValue();
What is Happening Now
When you use an unmarshal method that takes a class parameter, you are telling JAXB what class that XML corresponds to instead of having it automatically determined by the root element.
results = (HotelListResponse) JAXB.unmarshal(source, HotelListResponse.class)
Because the level of the XML document is wrong JAXB isn't able to match any of it to your domain model. Therefore only the default values are populated. This is why the result is full of values that are 0 or false.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<HotelListResponse xmlns="http://v3.hotel.wsapi.ean.com/">
<numberOfRoomsRequested>0</numberOfRoomsRequested>
<moreResultsAvailable>false</moreResultsAvailable>
<HotelList size="0" activePropertyCount="0"/>
</HotelListResponse>
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