XML to POJO JAVA - java

I have read other posts related to this issue but I could not fix my problem. I try to convert the following XML String to a JAVA class but when I try to access param1 using getParam1() method it returns null and I am not sure why.
The XML String:
<?xml version="1.0" encoding="utf-8"?>
<REQUERYTRXRESPONSE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<param1>3gbahtJf1y85Oks4HrPLkqTQZV8Yg8pIhdXOrZ8pLGJP3FLwqKlIzIl/GgUpGvFaw4MC4SV+4pCudmVq+apIMIJJS4PrVyUx4T0ZO/Tsui4ZqCn62dLAG0DVhBVz2ZasF4yr7CRYnk47FWS0RywXmA==</param1>
<param2>lO4ismiJwsvBiHQGW/UwCA==</param2>
<param3 />
</REQUERYTRXRESPONSE>
The Java class:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(namespace = "http://tempuri.org/", name = "REQUERYTRXRESPONSE")
#XmlAccessorType(XmlAccessType.PROPERTY)
public class REQUERYTRXRESPONSE {
private String param1;
private String param2;
private String param3;
#XmlElement(required = true, name = "param1")
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
#XmlElement(required = true, name = "param2")
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
#XmlElement(required = true, name = "param3")
public String getParam3() {
return param3;
}
public void setParam3(String param3) {
this.param3 = param3;
}
}
The XML to Java class code:
HttpRequest httpRequest = HttpRequest.get();
if (httpRequest.ok()) {
String response = httpRequest.body();
System.out.println(response);
JAXBContext jaxbContext = JAXBContext.newInstance(REQUERYTRXRESPONSE.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
REQUERYTRXRESPONSE requerytrxresponse = (REQUERYTRXRESPONSE) unmarshaller.unmarshal(new StringReader(response));
System.out.println((String) requerytrxresponse.getParam1()); // returns null
}

Managed to figure it out.
#XmlRootElement(name = "REQUERYTRXRESPONSE")
#XmlAccessorType(XmlAccessType.FIELD)
public class Response {
private String param1;
private String param2;
private String param3;
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
public String getParam3() {
return param3;
}
public void setParam3(String param3) {
this.param3 = param3;
}
}
You don't need to specify the #XmlElement when you do the #XxmlAccessorType unless you wanted the required=true part.
What I changed is that I moved the namespace from #XmlRootElement in a package-info.java class like so:
#javax.xml.bind.annotation.XmlSchema(namespace = "http://tempuri.org/",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.sfatandrei.soplayground.model;
My main test method includes:
final InputStream resourceAsStream = SoPlaygroundApplication.class.getClassLoader().getResourceAsStream("test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(resourceAsStream);
System.out.println(response);

For me it works just fine. Make sure that you've got a proper encoding and check your jaxb provider. I tested it with default sun implementation - com.sun.xml.bind.v2.runtime.JAXBContextImpl.
Make a test for your unmarshalling code:
#Test
public void testUnmarshaller() throws JAXBException, IOException {
final InputStream expectedXmlResource = getClass().getResourceAsStream("/REQUERYTRXRESPONSE.xml");
StringWriter stringWriter = new StringWriter();
IOUtils.copy(expectedXmlResource, stringWriter, "UTF-8");
JAXBContext jaxbContext = JAXBContext.newInstance(REQUERYTRXRESPONSE .class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
REQUERYTRXRESPONSE requerytrxresponse = (REQUERYTRXRESPONSE) unmarshaller.unmarshal(new StringReader(stringWriter.toString()));
assertEquals(requerytrxresponse.getParam1(), "3gbahtJf1y85Oks4HrPLkqTQZV8Yg8pIhdXOrZ8pLGJP3FLwqKlIzIl/GgUpGvFaw4MC4SV+4pCudmVq+apIMIJJS4PrVyUx4T0ZO/Tsui4ZqCn62dLAG0DVhBVz2ZasF4yr7CRYnk47FWS0RywXmA==");
}

Related

jaxb unmarshal to object by type

I want to parse out different types based on xml, when header=1 then User, header=2 then Order etc. for example:
<entity>
<header>1</header>
<body>
<userId>1</userId>
<userName>jonh</userName>
...
<body>
</entity>
<entity>
<header>2</header>
<body>
<orderId>1</orderId>
<orderNo>20200101</orderNo>
...
<body>
</entity>
How to implement this function?
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object object = unmarshaller.unmarshal(xml);
I would try this: provide the type when unmarshalling. So maybe do something like this: create a transient facade object:
public class XmlEntityFacade {
private int header;
private Object body;
//getters and setters...
}
And then cast this type while unmarshalling:
...
XmlEntityFacade facade = (XmlEntityFacade) unmarshaller.unmarshal(xml);
Then you can access the value of the by calling .getHeader() and body with .getBody() (getters that you have provided XmlEntityFacade class). And then depending on the value cast the required type to the Object.
public class TwiceUnmarshalTest {
#Data
#ToString
public static abstract class HeaderResponse {
private String header;
}
#XmlRootElement(name = "entity")
#XmlAccessorType(XmlAccessType.FIELD)
public static class XmlHeaderResponse extends HeaderResponse {
}
private final String xml = "<entity>" +
" <header>2</header>" +
" <body>" +
" <orderId>1</orderId>" +
" <orderNo>2020</orderNo>" +
" </body>" +
"</entity>";
#SuppressWarnings("unchecked")
public static <T> T unmarshal(Reader reader, Class<T> typeClass) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(typeClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return (T) unmarshaller.unmarshal(reader);
}
#Test
public void headerResponse() throws Exception {
HeaderResponse response = unmarshal(new StringReader(xml), XmlHeaderResponse.class);
System.out.println(response);
}
#ToString(callSuper = true)
public static abstract class Response<T> extends HeaderResponse {
#XmlAnyElement(lax = true)
public T body;
}
#Data
#XmlRootElement(name = "body")
public static class Order {
private String orderId;
private String orderNo;
}
#XmlRootElement(name = "entity")
#XmlSeeAlso({Order.class})
public static class OrderResponse extends Response<Order> {
}
#Test
public void response() throws Exception {
XmlHeaderResponse response = unmarshal(new StringReader(xml), XmlHeaderResponse.class);
System.out.println(response);
//TwiceUnmarshalTest.HeaderResponse(header=2)
if (response.getHeader().equals("2")) {
OrderResponse orderResponse = unmarshal(new StringReader(xml), OrderResponse.class);
System.out.println(orderResponse);
//TwiceUnmarshalTest.Response(super=TwiceUnmarshalTest.HeaderResponse(header=2), body=TwiceUnmarshalTest.Order(orderId=1, orderNo=2020))
}
}
}
unmarshal twice, just get the header first, then get the entity. Not very good but can be used.

How to name complex objects in JAXB/JSON?

#XmlRootElement(name = "test")
public class MyDTO {
#XmlElement(name = "test2)
private MyObject meta;
}
Result:
{meta:{...}}
Problems:
I'd like to have some kind of "outer" tag named "test"
Why is the #XmlElement(name" attribute for meta not working?
my first post!
Indeed you can name your "outer" tag with #XmlRootElement. If you need another outer tag I am not sure how to realize this.
Your second concern might be because of the place where you put the #XmlElement. I placed it on my getter-method and it worked fine fore me.
For the JSON Output I used jersey-json-1.18.
The following works also for other complex types you could define instead of "String meta".
Here is the output I was able to produce:
As JSON
{"myId":"id1","myMeta":"text1"}
As XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mytupel>
<myId>id1</myId>
<myMeta>text1</myMeta>
</mytupel>
This is my object:
#XmlRootElement(name = "mytupel")
public class Tupel {
// #XmlElement(name = ) does not work here - defined it on the getter method
private String id;
// #XmlElement(name = ) does not work here - defined it on the getter method
private String meta;
/**
* Needed for JAXB
*/
public Tupel() {
}
/**
* For Test purpose...
*/
public Tupel(String id, String text) {
super();
this.id = id;
this.meta = text;
}
#XmlElement(name = "myId")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlElement(name = "myMeta")
public String getMeta() {
return meta;
}
public void setMeta(String meta) {
this.meta = meta;
}
/**
* For Test purpose...
*/
#Override
public String toString() {
return id + ": " + meta;
}
}
And here is my small class to produce the output XML files...
public class Main {
private static final String TUPEL_1_XML = "./tupel1.xml";
private static final String TUPEL_2_XML = "./tupel2.xml";
public static void main(String[] args) throws JAXBException, FileNotFoundException {
// init JAXB context/Marhsaller stuff
JAXBContext context = JAXBContext.newInstance(Tupel.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
Unmarshaller unmarshaller = context.createUnmarshaller();
// create some Datatypes
Tupel data1 = new Tupel("id1", "text1");
Tupel data2 = new Tupel("id2", "42");
// produce output
marshaller.marshal(data1, new File(TUPEL_1_XML));
marshaller.marshal(data2, new File(TUPEL_2_XML));
// read from produced output
Tupel data1FromXml = (Tupel) unmarshaller.unmarshal(new FileReader(TUPEL_1_XML));
Tupel data2FromXml = (Tupel) unmarshaller.unmarshal(new FileReader(TUPEL_2_XML));
System.out.println(data1FromXml.toString());
System.out.println(data2FromXml.toString());
System.out.println(marshalToJson(data1FromXml));
System.out.println(marshalToJson(data2FromXml));
}
public static String marshalToJson(Object o) throws JAXBException {
StringWriter writer = new StringWriter();
JAXBContext context = JSONJAXBContext.newInstance(o.getClass());
Marshaller m = context.createMarshaller();
JSONMarshaller marshaller = JSONJAXBContext.getJSONMarshaller(m, context);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshallToJSON(o, writer);
return writer.toString();
}
}
Hope this answers your question!
Cheers
Max

Java Unmarshal list of objects with a class wrapper with JAXB

From an XQuery performed by BaseX server I get a result like that:
<ProtocolloList>
<protocollo>
<numero>1</numero>
<data>2014-06-23</data>
<oggetto/>
<destinatario/>
<operatore/>
</protocollo>
...
</ProtocolloList>
And I need to convert this result in a List of Protocollo objects with JAXB so that I can show them with JList. Thus, following one of the discussions here I've declared the following classes:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "protocollo")
public class Protocollo {
private int numero;
private String data;
private String oggetto;
private String destinatario;
private String operatore;
public Protocollo(String d, String o, String des, String op) {
this.data = d;
this.oggetto = o;
this.destinatario = des;
this.operatore = op;
}
public Protocollo() {
}
#XmlElement
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
#XmlElement
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
#XmlElement
public String getOggetto() {
return oggetto;
}
public void setOggetto(String oggetto) {
this.oggetto = oggetto;
}
#XmlElement
public String getDestinatario() {
return destinatario;
}
public void setDestinatario(String destinatario) {
this.destinatario = destinatario;
}
#XmlElement
public String getOperatore() {
return operatore;
}
public void setOperatore(String operatore) {
this.operatore = operatore;
}
}
and
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "ProtocolloList")
public class ProtocolloList {
#XmlElementWrapper(name = "ProtocolloList")
#XmlElement(name = "protocollo")
private ArrayList<Protocollo> ProtocolloList;
public ArrayList<Protocollo> getProtocolloList() {
return ProtocolloList;
}
public void setProtocolloList(ArrayList<Protocollo> protocolloList) {
ProtocolloList = protocolloList;
}
}
and finally I execute the converion like that:
JAXBContext jaxbContext = JAXBContext.newInstance(Protocollo.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(this.resultXML);
protocolli = (ProtocolloList) unmarshaller.unmarshal(reader);
And I keep on getting this exception:
unexpected element (uri:"", local:"ProtocolloList"). Expected elements are <{}protocollo>
I suppose I'm making some mistakes with annotations.
Can you help?
For your use case you do not need the #XmlElementWrapper annotation. This is because the ProtocolList element corresponds to your #XmlRootElement annotation. Then you need the #XmlElement annotation on the property to grab each of the list items.
#XmlRootElement(name = "ProtocolloList")
public class ProtocolloList {
private ArrayList<Protocollo> ProtocolloList;
#XmlElement(name = "protocollo")
public ArrayList<Protocollo> getProtocolloList() {
return ProtocolloList;
}
}
Note:
By default you should annotate the property. If you want to annotate the fields you should put #XmlAccessorType(XmlAccessType.FIELD) on your class.
UPDATE
You need to make sure your JAXBContext is aware of the root class. You can change your JAXBContext creation code to be the following:
JAXBContext jaxbContext = JAXBContext.newInstance(ProtocolloList.class);

Exception in thread "main" java.lang.NullPointerException when using Jaxb unmarshal/marshal

I'm using JAXB to unmarshal a given input Xml file into Java object
and then marashal it back to Xml String.
My Xml file looks like this:
<bpmn2:definitions xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" id="_Definitions_1">
<bpmn2:process id="_500441" name="process">
</bpmn2:process>
</bpmn2:definitions>
Definitions.class:
#XmlRootElement(namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL")
public class Definitions {
#XmlAttribute
private String id;
#XmlElement(name = "bpmn2:process")
private Process process;
#XmlElement(name = "bpmndi:BPMNDiagram")
private Diagram diagram;
public Definitions() {
}
public Definitions(String id, Process process, Diagram diagram) {
this.id = id;
this.process = process;
this.diagram = diagram;
}
public Process getProcess() {
return process;
}
public Diagram getDiagram() {
return diagram;
}
public String getId() {
return id;
}
}
Process.class:
#XmlAccessorType(XmlAccessType.FIELD)
public class Process {
#XmlAttribute
private String id;
public Process() {
}
public Process(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
Model.class:
public class Model {
#XmlElement
private Process process;
public Model() {
}
public Model(String processId, Process p) {
this.id = processId;
this.process = p;
}
}
main method:
public static void main(String[] args) throws IOException, JSONException, JAXBException {
BpmnToJsonImport bj = new BpmnToJsonImport();
InputStream is = BpmnToJsonImport.class.getResourceAsStream("myXml.txt");
String Str = IOUtils.toString(is);
StringReader sr = new StringReader(Str);
JAXBContext context = JAXBContext.newInstance(Definitions.class, Model.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Definitions d = (Definitions) unmarshaller.unmarshal(sr);
Model model = new Model(d.getProcess().getId(), d.getProcess());
StringWriter sw = new StringWriter();
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(model, sw);
String str = sw.toString();
System.out.println(str);
}
Exactly when it tries to retrieve the process id using d.getProcess.getId I get the
java.lang.NullPointerException
You are mapping the namespace qualification incorrectly. You must not include the prefix in the element name.
#XmlElement(name = "BPMNDiagram")
private Diagram diagram;
To map the namespace qualification you can use the package level #XmlSchema annotation.
package-info.java
#XmlSchema(
namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
For More Information
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html

Mapping nested xml elements to single Java Object

How would I map this
<urn:envelope xmlns:urn="urn:com.twinstrata.webservice:2.1">
<urn:encoded>
<urn:response>
<urn:license>
<urn:licenseTag>WHATEVER934</urn:licenseTag>
<urn:accountNumber>2016763117</urn:accountNumber>
<urn:licenseType>TRIAL</urn:licenseType>
<urn:licenseClass>Credentialed</urn:licenseClass>
<urn:volumeAllowed>Unlimited</urn:volumeAllowed>
<urn:volumeProvisioned>0</urn:volumeProvisioned>
<urn:snapshotLimit>Unlimited</urn:snapshotLimit>
<urn:snapshotLimitPerVolume>10</urn:snapshotLimitPerVolume>
<urn:status>Active</urn:status>
<urn:usedSpace>0</urn:usedSpace>
<urn:expirtationDate>2013-03-27 14:48:47.0</urn:expirtationDate>
<urn:storageLimit>Unlimited</urn:storageLimit>
</urn:license>
</urn:response>
</urn:encoded>
<urn:signature>Hl8rk2aTEsOkkq5e383LH0BqdFfmVcKIg9FuFEnnrlFk9fwYVEQwkrm/7MPM2Zmli2Um00L2Ab25tZg2w8pEzXyDsd+vwCAH0ypQwhIVPayDjgYKlYXbnkqG5S+7qiVbqD2qZDektuPoEWvaSdxO3ZgUibT+nnrO0kl6E7i4lB0=
</urn:signature>
to this
package com.folio3.bean;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "envelope" , namespace = "urn:com.twinstrata.webservice:2.1")
public class ResponseXML {
private String userName;
private String license;
private String signature;
private String licenseTag;
private String accountNumber;
private String licenseType;
private String licenseClass;
private String volumeAllowed;
private String volumeProvisioned;
private String publicKey;
#XmlElement(name = "userName" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#XmlElement(name = "license" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
#XmlElement(name = "signature" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
#XmlElement(name = "licenseTag" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getLicenseTag() {
return licenseTag;
}
public void setLicenseTag(String licenseTag) {
this.licenseTag = licenseTag;
}
#XmlElement(name = "accountNumber" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
#XmlElement(name = "licenseType" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getLicenseType() {
return licenseType;
}
public void setLicenseType(String licenseType) {
this.licenseType = licenseType;
}
#XmlElement(name = "licenseClass" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getLicenseClass() {
return licenseClass;
}
public void setLicenseClass(String licenseClass) {
this.licenseClass = licenseClass;
}
#XmlElement(name = "volumeAllowed" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getVolumeAllowed() {
return volumeAllowed;
}
public void setVolumeAllowed(String volumeAllowed) {
this.volumeAllowed = volumeAllowed;
}
#XmlElement(name = "volumeProvisioned" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getVolumeProvisioned() {
return volumeProvisioned;
}
public void setVolumeProvisioned(String volumeProvisioned) {
this.volumeProvisioned = volumeProvisioned;
}
#XmlElement(name = "publicKey" , namespace = "urn:com.twinstrata.webservice:2.1")
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ResponseXML [userName=");
builder.append(userName);
builder.append(", license=");
builder.append(license);
builder.append(", signature=");
builder.append(signature);
builder.append(", licenseTag=");
builder.append(licenseTag);
builder.append(", accountNumber=");
builder.append(accountNumber);
builder.append(", licenseType=");
builder.append(licenseType);
builder.append(", licenseClass=");
builder.append(licenseClass);
builder.append(", volumeAllowed=");
builder.append(volumeAllowed);
builder.append(", volumeProvisioned=");
builder.append(volumeProvisioned);
builder.append(", publicKey=");
builder.append(publicKey);
builder.append("]");
return builder.toString();
}
}
Currently , It maps only one property of XML , that is "signature".
For the sake of simplicity, I don't want to make other classes and nest the objects inside it. I just want to parse nested xml tags in single Java class.
How do I do that ?
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
ResponseXML
You could use MOXy's #XmlPathextension to map your use case (see: http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html). Below is a partial mapping of your use case.
package forum15391077;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name = "envelope")
#XmlType(propOrder={"licenseTag", "accountNumber", "licenseType", "licenseClass", "volumeAllowed", "volumeProvisioned", "signature", "license", "publicKey", "userName"})
#XmlAccessorType(XmlAccessType.FIELD)
public class ResponseXML {
private String userName;
private String license;
private String signature;
#XmlPath("urn:encoded/urn:response/urn:license/urn:licenseTag/text()")
private String licenseTag;
#XmlPath("urn:encoded/urn:response/urn:license/urn:accountNumber/text()")
private String accountNumber;
#XmlPath("urn:encoded/urn:response/urn:license/urn:licenseType/text()")
private String licenseType;
#XmlPath("urn:encoded/urn:response/urn:license/urn:licenseClass/text()")
private String licenseClass;
#XmlPath("urn:encoded/urn:response/urn:license/urn:volumeAllowed/text()")
private String volumeAllowed;
#XmlPath("urn:encoded/urn:response/urn:license/urn:volumeProvisioned/text()")
private String volumeProvisioned;
private String publicKey;
}
package-info
We will use the package level #XmlSchema annotation to specify the namespace qualification (see: http://blog.bdoughan.com/2010/08/jaxb-namespaces.html). We will also use it to define the urn prefix which we leveraged in the #XmlPath annotation.
#XmlSchema(
namespace="urn:com.twinstrata.webservice:2.1",
elementFormDefault=XmlNsForm.QUALIFIED,
xmlns={
#XmlNs(namespaceURI = "urn:com.twinstrata.webservice:2.1", prefix = "urn")
}
)
package forum15391077;
import javax.xml.bind.annotation.*;
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
Since MOXy is a standard JAXB implementation, the standard JAXB runtime APIs are used.
package forum15391077;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ResponseXML.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum15391077/input.xml");
ResponseXML response = (ResponseXML) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(response, System.out);
}
}
input.xml/Output
Below is a sample XML document based on the part of your use case that I mapped.
<?xml version="1.0" encoding="UTF-8"?>
<urn:envelope xmlns:urn="urn:com.twinstrata.webservice:2.1">
<urn:encoded>
<urn:response>
<urn:license>
<urn:licenseTag>WHATEVER934</urn:licenseTag>
<urn:accountNumber>2016763117</urn:accountNumber>
<urn:licenseType>TRIAL</urn:licenseType>
<urn:licenseClass>Credentialed</urn:licenseClass>
<urn:volumeAllowed>Unlimited</urn:volumeAllowed>
<urn:volumeProvisioned>0</urn:volumeProvisioned>
</urn:license>
</urn:response>
</urn:encoded>
<urn:signature>Hl8rk2aTEsOkkq5e383LH0BqdFfmVcKIg9FuFEnnrlFk9fwYVEQwkrm/7MPM2Zmli2Um00L2Ab25tZg2w8pEzXyDsd+vwCAH0ypQwhIVPayDjgYKlYXbnkqG5S+7qiVbqD2qZDektuPoEWvaSdxO3ZgUibT+nnrO0kl6E7i4lB0=
</urn:signature>
</urn:envelope>
I made it working by creating nested classes and by using proper JAXB annotations.

Categories

Resources