How to marshal/unmarshal abstract class with a different tags using JAXB - jaxb

<root-object>
<synchronous>
<command>C:\hello_world.exe</command>
<argument>aaaa</argument>
<argument>bbbb</argument>
</synchronous>
<asynchronous>
<command>C:\hello_world.exe</command>
<argument>aaaa</argument>
<argument>bbbb</argument>
</asynchronous>
<synchronous>
<command>C:\hello_world.exe</command>
<argument>aaaa</argument>
<argument>bbbb</argument>
</synchronous>
</root-object>
In this XML format, I want to unmarshal/marshal synchronous and asynchronous objects into a single list through JAXB.
I wrote the code as below, but nothing was entered in the items.
How can I make be this structure possible?
#XmlRootElement(name = "root-object")
#XmlAccessorType(XmlAccessType.FIELD)
#lombok.ToString
public class RootObject {
#XmlElement(type = CommandItem.class)
private List<CommandItem> items= new ArrayList<>();
public RootObject() {}
#lombok.Getter
#lombok.Setter
#lombok.NoArgsConstructor
#XmlType
#XmlSeeAlso({AsyncCommandItem.class, SyncCommandItem.class})
#XmlAccessorType(XmlAccessType.FIELD)
public static class CommandItem {
#XmlElement(name = "command")
private String command;
#XmlElement(name = "argument")
private List<String> argument;
}
#lombok.NoArgsConstructor
#XmlRootElement(name = "synchronous")
public static class SyncCommandItem extends CommandItem {
}
#lombok.NoArgsConstructor
#XmlRootElement(name = "asynchronous")
public static class AsyncCommandItem extends CommandItem {
}
}

I used the following code for the XML you have provided and it seems to work fine for me. You need to modify the POJO a bit in order to make it work.
RootObject.class:
#XmlRootElement(name = "root-object")
#Data
#XmlAccessorType(XmlAccessType.FIELD)
public class RootObject {
#XmlElement(name = "synchronous")
private List<Synchronous> synchronous;
#XmlElement(name = "asynchronous")
private List<Asynchronous> asynchronous;
}
Synchronous.class:
#Data
#XmlAccessorType(XmlAccessType.NONE)
public class Synchronous {
#XmlElement(name = "command")
private String command;
#XmlElement(name = "argument")
private List<String> argument;
}
Asynchronous.class:
#Data
#XmlAccessorType(XmlAccessType.NONE)
public class Asynchronous {
#XmlElement(name = "command")
private String command;
#XmlElement(name = "argument")
private List<String> argument;
}
Main.class:
public class Main {
public static void main(String[] args) throws JAXBException, XMLStreamException {
final InputStream inputStream = Unmarshalling.class.getClassLoader().getResourceAsStream("synchronous.xml");
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
final Unmarshaller unmarshaller = JAXBContext.newInstance(RootObject.class).createUnmarshaller();
final RootObject rootObject = unmarshaller.unmarshal(xmlStreamReader, RootObject.class).getValue();
System.out.println(rootObject.toString());
Marshaller marshaller = JAXBContext.newInstance(RootObject.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(rootObject, System.out);
}
}
Following is the output:
RootObject(synchronous=[Synchronous(command=C:\hello_world.exe, argument=[aaaa, bbbb]), Synchronous(command=C:\hello_world.exe, argument=[aaaa, bbbb])], asynchronous=[Asynchronous(command=C:\hello_world.exe, argument=[aaaa, bbbb])])
<root-object>
<synchronous>
<command>C:\hello_world.exe</command>
<argument>aaaa</argument>
<argument>bbbb</argument>
</synchronous>
<synchronous>
<command>C:\hello_world.exe</command>
<argument>aaaa</argument>
<argument>bbbb</argument>
</synchronous>
<asynchronous>
<command>C:\hello_world.exe</command>
<argument>aaaa</argument>
<argument>bbbb</argument>
</asynchronous>
</root-object>

I solved it by #XmlElements.
#XmlRootElement(name = "root-object")
#XmlAccessorType(XmlAccessType.FIELD)
#lombok.ToString
public class RootObject {
#XmlElements({
#XmlElement(name = "synchronous", type = SyncCommandItem.class),
#XmlElement(name = "asynchronous", type = AsyncCommandItem .class),
})
private List<CommandItem> items= new ArrayList<>();
public RootObject() {}
#lombok.Getter
#lombok.Setter
#lombok.NoArgsConstructor
#XmlType
#XmlSeeAlso({AsyncCommandItem.class, SyncCommandItem.class})
#XmlAccessorType(XmlAccessType.FIELD)
public static class CommandItem {
#XmlElement(name = "command")
private String command;
#XmlElement(name = "argument")
private List<String> argument;
}
#lombok.NoArgsConstructor
#XmlRootElement(name = "synchronous")
public static class SyncCommandItem extends CommandItem {
}
#lombok.NoArgsConstructor
#XmlRootElement(name = "asynchronous")
public static class AsyncCommandItem extends CommandItem {
}
}

Related

Create xml string for java jaxb bean with Root class & inner classes having different name spaces

I have a Root Class called Employee, which has two elements empid and name and another jaxb class called Address. Below is the sample snippet.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Request",propOrder = {
"header",
"body",
"signature"
})
#XmlRootElement(name="Employee")
public class Employee
implements Serializable
{
#XmlElement(name = "Header", required = true)
protected String empId;
#XmlElement(name = "Body", required = true)
protected String empName;
#XmlElement(name = "Address", required = true)
protected Address address;
.. setters and getters
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Address", propOrder = {
"streetLine1",
"streetLine2",
})
#XmlRootElement(name="Address",namespace= "http://www.w3.org/2000/09/xmldsig#")
public class Employee
implements Serializable
{
private final static long serialVersionUID = 100L;
#XmlElement(name = "addressLine1", required = true)
protected String addressLine1;
#XmlElement(name = "addressLine2", required = true)
protected String addressLine2;
//Setters and getters
}
Now when I generate the XML string with jaxb marshalling I want the expected result like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee xmlns="http://www.test.com">
<empId>124</empId>
<empName>name</empName>
<Address xmlns:ns2="http://www.w3.org/2000/09/xmldsig#">
<ns2:streetLine1 Id="line1"/>
<ns2:streetLine2 Id="Line2"/>
</Address>
</Request>
Please suggest. Thanks in Advance.
There are some problems with your JAXB classes, I think you have copy pasted and changed some names wrongly. The following elements inside #XMLType must be defined as #XMLElement.
#XmlType(name = "Request",propOrder = {
"header",
"body",
"signature"
})
Anyways assuming the classes are right. You will need 2 changes to generate XML that has elements referred in different namespace.
Move the namespace to package level using #XMLSchema. i.e Add package-info.java at the package level to specify the namespaces.
Provide Address element with its own namespace in Employee class. Each element if not in parent namespace, must be overridden at this level.
package-info.java
#XmlSchema(
namespace = "http://www.test.com",
elementFormDefault = XmlNsForm.QUALIFIED)
package int1.d;
import javax.xml.bind.annotation.*;
Employee.java
package int1.d;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Request",propOrder = {
"header",
"body",
"signature"
})
#XmlRootElement(name="Employee")
public class Employee
implements Serializable
{
private static final long serialVersionUID = 8293193254658211943L;
#XmlElement(name = "Header", required = true)
protected String empId;
#XmlElement(name = "Body", required = true)
protected String empName;
#XmlElement(name = "Address", namespace="http://www.w3.org/2000/09/xmldsig#", required = true )
protected Address address;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package-info.java
#XmlSchema(
namespace = "http://www.w3.org/2000/09/xmldsig#",
elementFormDefault=XmlNsForm.QUALIFIED )
package int1.d2;
import javax.xml.bind.annotation.*;
Address.java
package int1.d2;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Address", propOrder = {
"streetLine1",
"streetLine2",
})
#XmlRootElement(name="Address")
public class Address
implements Serializable
{
private final static long serialVersionUID = 100L;
#XmlElement(name = "addressLine1", required = true)
protected String addressLine1;
#XmlElement(name = "addressLine2", required = true)
protected String addressLine2;
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
}
output generated by JAXB
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee xmlns="http://www.test.com" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#">
<Header>124</Header>
<Body>bae</Body>
<ns2:Address>
<ns2:addressLine1>line1</ns2:addressLine1>
<ns2:addressLine2>line2</ns2:addressLine2>
</ns2:Address>
</Employee>

JAXB Marshalling: Creating an empty element with an attribute

I use a JAXB marshaller and I would like to add an empty element with a specific attribute. This is a dummy class:
#XmlRootElement(name="observation")
public class Observation {
#XmlAttribute
public static final String classCode = "OBS";
#XmlAttribute
public static final String moodCode = "EVN";
private String data;
#XmlElement
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
This creates the following XML:
<observation classCode="OBS" moodCode="EVN">
<data>fsdfsdfd</data>
</observation>
Is there any way to add a new element with a specific attribute only (no value at all)? E.g.
<observation classCode="OBS" moodCode="EVN">
<templateId root="2.16.840.1.113883.10.20.1.31"/>
<data>fsdfsdfd</data>
</observation>
This should do it:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "TemplateIdType")
public class TemplateIdType {
#XmlAttribute(name = "root")
protected String root;
// getter and setter
}
(And you add an element of this class to Observation.)

Creating null object for input StringReader using JAXBContext

I am trying to create bean from string but unable to create as it is returning null.Here is my code
public ModelAndView checkPhotoQualityRequest(
#RequestBody String photoDataXml, HttpServletRequest request) {
PhotoQuality photoQuality = null;
try {
JAXBContext jaxbContext = JAXBContext
.newInstance(PhotoQuality.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(photoDataXml);
photoQuality = (PhotoQuality) unmarshaller.unmarshal(reader);
PhotoQuality.java
package in.gov.uid.opencvaccess.bean;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType(name = "PhotoQuality")
#XmlRootElement(name = "PhotoQuality")
public class PhotoQuality {
private String photoid;
private byte[] photo;
private boolean quality;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPhotoid() {
return photoid;
}
public void setPhotoid(String photoid) {
this.photoid = photoid;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public boolean isQuality() {
return quality;
}
public void setQuality(boolean quality) {
this.quality = quality;
}
}
Please help me to sort out this issue.When I debug and check bean its showing all null values but photoDataXml showing complete xml.
I have found the reason.When I tried using RESTClient its giving null object. But as soon as I written client code and passed StringWriter value created from PhotoQuality Object then it runs properly.

JAXB and inheritance

I am trying to read a JSON file like:
{
"a": "abc",
"data" : {
"type" : 1,
...
}
}
where the ... part is replaceable based on the type like:
{
"a": "abc",
"data" : {
"type" : 1,
"b" : "bcd"
}
}
or:
{
"a": "abc",
"data" : {
"type" : 2,
"c" : "cde",
"d" : "def",
}
}
For the life of me I cannot figure out the proper JAXB annotations/classes to use to make this happen.
I don't have an issue moving the type variable outside of the data block if needed.
I'm using Glassfish 3.1.2.2.
Edit:
Based on the code provided by Perception I did a quick attempt... doesn't work in glassfish though:
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type")
#JsonSubTypes(
{
#JsonSubTypes.Type(value = DataSubA.class, name = "1"),
#JsonSubTypes.Type(value = DataSubB.class, name = "2")
})
#XmlRootElement
public abstract class Data implements Serializable
{
private static final long serialVersionUID = 1L;
public Data()
{
super();
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class DataSubA
extends Data
{
private static final long serialVersionUID = 1L;
#XmlElement
private BigDecimal expenditure;
public DataSubA() {
super();
}
public DataSubA(final BigDecimal expenditure) {
super();
this.expenditure = expenditure;
}
#Override
public String toString() {
return String.format("%s[expenditure = %s]\n",
getClass().getSimpleName(), getExpenditure());
}
public BigDecimal getExpenditure() {
return expenditure;
}
public void setExpenditure(BigDecimal expenditure) {
this.expenditure = expenditure;
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class DataSubB
extends Data
{
private static final long serialVersionUID = 1L;
#XmlElement
private String name;
#XmlElement
private Integer age;
public DataSubB()
{
super();
}
public DataSubB(final String name, final Integer age)
{
super();
this.name = name;
this.age = age;
}
#Override
public String toString()
{
return String.format("%s[name = %s, age = %s]\n",
getClass().getSimpleName(), getName(), getAge());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class DataWrapper
{
#XmlElement
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
And a simple POST that takes it in:
#Stateless
#Path("x")
public class Endpoint
{
#POST
#Consumes(
{
MediaType.APPLICATION_JSON,
})
#Produces(
{
MediaType.APPLICATION_JSON,
})
public String foo(final DataWrapper wrapper)
{
return ("yay");
}
}
When I pass in JSON like:
{
"data" :
{
"type" : 1,
"expenditure" : 1
}
}
I get a message like:
Can not construct instance of Data, problem: abstract types can only be instantiated with additional type information
at [Source: org.apache.catalina.connector.CoyoteInputStream#28b92ec1; line: 2, column: 5] (through reference chain: DataWrapper["data"])
On the DataClass add an #XmlSeeAlso annotation that specifies all of the subclasses:
#XmlRootElement
#XmlSeeAlso({DataSubA.class, DataSubB.class})
public abstract class Data implements Serializable {
Then on each of the subclasses use the #XmlType annotation to specify the type name.
#XmlType(name="1")
public class DataSubA extends Data {
UPDATE
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
The JAXB (JSR-222) specification doesn't cover JSON-binding. There are different ways JAX-RS allows you to specify JSON mapping via JAXB annotations:
A JAXB implementation plus a library like Jettison that converts StAX events to JSON (see: http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html)
By leveraging a JAXB impl that offers a JSON-binding (see: http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html)
Leveraging a JSON-binding tool that offers support for some JAXB metadata (i.e Jackson).
Since your model doesn't seem to be reacting as expected to the annotations I'm guessing you are using scenario 3. Below I will demonstrate the solution as if you were using scenario 2.
DataWrapper
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class DataWrapper {
private String a;
private Data data;
}
Data
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlSeeAlso({DataSubA.class, DataSubB.class})
public class Data {
}
DataSubA
import javax.xml.bind.annotation.XmlType;
#XmlType(name="1")
public class DataSubA extends Data {
private String b;
}
DataSubB
import javax.xml.bind.annotation.XmlType;
#XmlType(name="2")
public class DataSubB extends Data {
private String c;
private String d;
}
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
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {DataWrapper.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource json = new StreamSource("src/forum16429717/input.json");
DataWrapper dataWrapper = unmarshaller.unmarshal(json, DataWrapper.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(dataWrapper, System.out);
}
}
input.json/Output
MOXy can read in the numeric value 2 as the inheritance indicator, but currently it will always write it out as "2". I have opened the following enhancement request to address this issue: http://bugs.eclipse.org/407528.
{
"a" : "abc",
"data" : {
"type" : "2",
"c" : "cde",
"d" : "def"
}
}
For More Information
The following link will help you use MOXy in a JAX-RS implementation.
http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html

Can JAXB/MOXy serialize enums in the same way as regular classes (non-enums)?

Imagine I have enum defined like this:
public enum ArchiveStatus implements Serializable {
CANDIDATE (0, "CANDIDATE", "Candidate for archival"),
IN_LIBRARY (1, "IN-LIBRARY", ".."),
FROM_LIBRARY (2, "FROM-LIBRARY", "..");
private int id;
private String shortName;
private String longName;
public ArchiveStatus( int id, String shortName, String longName ) {
..
}
public int getId() { .. }
public String getShortName() { .. }
public String getLongName() { .. }
}
By default MOXy is going to serialize it to JSON like this:
{
..
"archiveStatus": "CANDIDATE",
..
}
Is there a way to configure MOXy (in the mapping file) to serialize the enum like a regular class:
{
..
"archiveStatus": { "id" : 0, "shortName": "CANDIDATE", "longName": "Candidate for archival" },
..
}
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
ArchiveStatusAdapter
You can solve this use case by leveraging an XmlAdapter. XmlAdapter is a JAXB mechanism that allows you to marshal one type of object as another.
package forum10144489;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ArchiveStatusAdapter extends XmlAdapter<ArchiveStatusAdapter.AdaptedArchiveStatus, ArchiveStatus> {
public static class AdaptedArchiveStatus {
public int id;
public String shortName;
public String longName;
}
#Override
public ArchiveStatus unmarshal(AdaptedArchiveStatus adaptedArchiveStatus) throws Exception {
if(null == adaptedArchiveStatus) {
return null;
}
return ArchiveStatus.valueOf(adaptedArchiveStatus.shortName);
}
#Override
public AdaptedArchiveStatus marshal(ArchiveStatus archiveStatus) throws Exception {
if(null == archiveStatus) {
return null;
}
AdaptedArchiveStatus adaptedArchiveStatus = new AdaptedArchiveStatus();
adaptedArchiveStatus.id = archiveStatus.getId();
adaptedArchiveStatus.longName = archiveStatus.getLongName();
adaptedArchiveStatus.shortName = archiveStatus.getShortName();
return adaptedArchiveStatus;
}
}
Root
The XmlAdapter can be specified at the field, property, type, or package level using the #XmlJavaTypeAdapter annotation.
package forum10144489;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class Root {
private ArchiveStatus archiveStatus;
#XmlJavaTypeAdapter(ArchiveStatusAdapter.class)
public ArchiveStatus getArchiveStatus() {
return archiveStatus;
}
public void setArchiveStatus(ArchiveStatus archiveStatus) {
this.archiveStatus = archiveStatus;
}
}
jaxb.properties
To specify MOXy as your JAXB provider you need to add a file called jaxb.properties in the same package as your domain classes with the following entry.
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
package forum10144489;
import java.io.StringReader;
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put("eclipselink.media-type", "application/json");
properties.put("eclipselink.json.include-root", false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StringReader jsonStringReader = new StringReader("{\"archiveStatus\" : {\"id\" : 0, \"shortName\" : \"CANDIDATE\", \"longName\" : \"Candidate for archival\"}}");
StreamSource jsonSource = new StreamSource(jsonStringReader);
Root root = unmarshaller.unmarshal(jsonSource, Root.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
Below is the output from running the demo code:
{
"archiveStatus" : {
"id" : 0,
"shortName" : "CANDIDATE",
"longName" : "Candidate for archival"
}
}
For More Information
http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html
http://blog.bdoughan.com/search/label/XmlAdapter
http://blog.bdoughan.com/search/label/jaxb.properties

Resources