JAXB not generating XML as per the Annotations (JDK 1.7) - java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
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;
public class JavaToXMLDemo {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Employee object = new Employee();
object.setCode("CA");
object.setName("Cath");
object.setSalary(300);
object.setProperties(new PropertiesMap());
m.marshal(object, System.out);
}
}
#XmlRootElement(name="Employee")
#XmlAccessorType(XmlAccessType.FIELD)
class Employee {
private String code;
#XmlElement(name = "Name")
private String name;
private int salary;
#XmlElement(name = "Properties")
protected PropertiesMap params;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public PropertiesMap getProperties() {
return params;
}
public void setProperties(PropertiesMap value) {
this.params = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int population) {
this.salary = population;
}
}
#XmlRootElement(name="Properties")
class PropertiesMap<K,V> extends HashMap<K,V>
{
}
The above code generates the below XML with JDK 1.6
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
<code>CA</code>
<Name>Cath</Name>
<salary>300</salary>
<Properties/>
</Employee>
and this on JDK 1.7
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
<code>CA</code>
<Name>Cath</Name>
<salary>300</salary>
<params/>
</Employee>
Why does the Marshaller behave differently?

You should use #XmlElementWrapper instead of #XmlElement for your Properties map.
See http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html use case #2.

Related

Object to xml tag and format soap envelope in Spring Boot

I am new in Spring Boot application i face an issue with xml format to soap envelope like below detail:
I need to convert object from java class to xml and format xml tag to soap envelop like below:
Bookstore.java
package com.example.wsdltojavaclass.xmlrequest;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "", namespace = "http://schemas.xmlsoap.org/soap/envelope/")
public class Bookstore {
#XmlElementWrapper(name = "bookList")
#XmlElement(name = "book")
private List < Book > bookList;
private String name;
private String location;
// public void setBookList(List < Book > bookList) {
// this.bookList = bookList;
// }
//
// public List < Book > getBooksList() {
// return bookList;
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
My Controller:
#GetMapping("/xml")
public void newroute() throws JAXBException, FileNotFoundException, JAXBException {
List<Book> bookList = new ArrayList<Book>();
Bookstore bookstore = new Bookstore();
bookstore.setName("Amazon Bookstore");
bookstore.setLocation("Newyorkt");
convertObjectToXML(bookstore);
}
private static void convertObjectToXML(Bookstore bookstore) throws JAXBException, FileNotFoundException {
JAXBContext context = JAXBContext.newInstance(Bookstore.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(bookstore, System.out);
m.marshal(bookstore, new File(BOOKSTORE_XML));
}
And here is my result:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2: xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/">
<name>Amazon Bookstore</name>
<location>Newyorkt</location>
</ns2:>
My expected result i need to change remove <?xml version="1.0" encoding="UTF-8" standalone="yes"?> and change format to
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://www.dataaccess.com/webservicesserver/">
<soap:Header/>
<soap:Body>
<web:name>Amazon Bookstore</web:name>
<web:location>Newyorkt</web:location>
</soap:Body>
</soap:Envelope>
So how to change from ns2 to soap envelope?

storing multiple objects in XML file

I have a simple java program to write an object to a xml file, my problem is that no matter how I do it, I can just store 1 object in the xml file.
my code goes as follows
import javax.xml.bind.annotation.XmlAttribute ;
import javax.xml.bind.annotation.XmlElement ;
import javax.xml.bind.annotation.XmlRootElement ;
#XmlRootElement
public class Product {
String Name;
int Price;
#XmlElement
public void setName(String Name) {
this.Name = Name;
}
#XmlElement
public void setPrice(int price) {
this.price = price;
}
}
import xml.Product;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class XML {
public static void main(String[] args) {
Product product=new Product();
product.setName("Hamburger");
product.setPrice(10);
try{
//File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(product, file);
jaxbMarshaller.marshal(product, System.out);
}catch(JAXBException e){
e.printStackTrace();
}
}
}
but even if I instance 2 products, I get just one object in my XML file(which is written correctly)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Product>
<Name>Hamburger</Name>
<price>10</price>
</Product>
You can fix this by using a List of Product for example
Here is Product.java refactored:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "product")
#XmlAccessorType (XmlAccessType.FIELD)
public class Product {
private String Name;
private int price;
public String getName() {
return Name;
}
public int getPrice() {
return price;
}
public void setName(String Name) {
this.Name = Name;
}
public void setPrice(int price) {
this.price = price;
}
}
Now create a Products entity that will have a field of type List
import java.util.List;
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(name = "products")
#XmlAccessorType (XmlAccessType.FIELD)
public class Products {
#XmlElement(name = "product")
private List<Product> products = null;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
And finally a demo:
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class ProductsDump {
static Products products = new Products();
static
{
products.setProducts(new ArrayList<>());
Product prod1 = new Product();
prod1.setName("Hamburger");
prod1.setPrice(10);
Product prod2 = new Product();
prod2.setName("Bretzel");
prod2.setPrice(5);
products.getProducts().add(prod1);
products.getProducts().add(prod2);
}
private static void marshalingExample() throws JAXBException
{
JAXBContext jaxbContext = JAXBContext.newInstance(Products.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Marshal the products list in console
jaxbMarshaller.marshal(products, System.out);
//Marshal the products list in file
jaxbMarshaller.marshal(products, new File("c:/products.xml"));
}
public static void main(String[] args) throws Exception {
marshalingExample();
}
}
Hmm, this is kind of like asking if it's plugged in, but your example only has thing. You need a list of some sort. Add the products to the list and then serialize the list.
Also take a look at XStream, you can get it to do the xml bits for you and you won't have to deal with the javax stuff. It'll serialize to and from XML for you.

How to avoid root element annotation while marshalling in JAXB?

I want to store my object data to XML. Below code spinets will show the example of model class.
Class Model
{
#XmlElement
private int id;
#XmlElement
Private string name;
}
I will have multiple model objects which will be stored in some list as below
#XmlRootElement
Class ModelWrapper
{
#XmlElement
#XmlJavaTypeAdapter(value = ListAdapter.class, type = List.class)
List<model> list;
public setlist(List<model>list)
{
//setting list
}
public List<model> getlist()
{
return list
}
}
Now if I marshall this using JAXB, something like this will be produced:
<Modelwrapper>
<List>
......
......
</List>
</Modelwrapper>
I want to avoid one of the root may be list or Modelwrapper.
Is there any way to do it?
In this way your xml will be
<ModelWrapper>
<model>
......
</model>
<model>
......
</model>
</ModelWrapper>
ModelWrapper.java
#XmlRootElement
public class ModelWrapper {
#XmlElement(name = "model")
protected List<Model> list;
Test
ModelWrapper.java
import java.util.List;
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;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "ModelWrapper", propOrder = {
"list"
})
public class ModelWrapper {
#XmlElement(name = "model")
private List<Model> list;
public List<Model> getList() {
return list;
}
public void setList(List<Model> list) {
this.list = list;
}
}
Model.java
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;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Model", propOrder = {
"id","name"
})
public class Model {
#XmlElement
private int id;
#XmlElement
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main.java
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Main {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(ModelWrapper.class);
ModelWrapper mw = new ModelWrapper();
List<Model> list = new ArrayList<Model>();
Model m = new Model();
m.setId(1);
m.setName("model1");
list.add(m);
m = new Model();
m.setId(1);
m.setName("model2");
list.add(m);
mw.setList(list);
Marshaller mar = jc.createMarshaller();
mar.marshal(mw, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<modelWrapper>
<model>
<id>1</id>
<name>model1</name>
</model>
<model>
<id>1</id>
<name>model2</name>
</model>
</modelWrapper>

JAXB - Reference to id with interface,abstract and list<abstract> [duplicate]

I'm wondering if it's possible to annotate my classes so that the first time the marshaller encounters an object, it generates an XML element of the appropriate type, but any subsequent reference to this object by anything else will have an XML IDREF entry created?
You can leverage the concept of JAXB's XmlAdapter to do something like the following:
input.xml
The following is the XML document I will use for this example. The 3rd phone-number entry is a reference to the 1st phone-number entry, and the 5th phone-number entry is a reference to the 4th.:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<phone-number id="A">
<number>555-AAAA</number>
</phone-number>
<phone-number id="B">
<number>555-BBBB</number>
</phone-number>
<phone-number id="A"/>
<phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W">
<number>555-WORK</number>
<extension>1234</extension>
</phone-number>
<phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"/>
</customer>
Customer
The customer class maintains a collection of PhoneNumber objects. The same instance of PhoneNumber may appear multiple times in the collection.
package forum7587095;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
private List<PhoneNumber> phoneNumbers;
#XmlElement(name="phone-number")
public List<PhoneNumber> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
PhoneNumber
This is a class that can either appear in the document itself or as a reference. This will be handled using an XmlAdapter. An XmlAdapter is configured using the #XmlJavaTypeAdapter annotation. Since we have specified this adapter at the type/class level it will apply to all properties referencing the PhoneNumber class:
package forum7587095;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlJavaTypeAdapter(PhoneNumberAdapter.class)
public class PhoneNumber {
private String id;
private String number;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#Override
public boolean equals(Object arg0) {
if(null == arg0 || arg0.getClass() != this.getClass()) {
return false;
}
PhoneNumber test = (PhoneNumber) arg0;
if(!equals(id, test.getId())) {
return false;
}
return equals(number, test.getNumber());
}
protected boolean equals(String control, String test) {
if(null == control) {
return null == test;
} else {
return control.equals(test);
}
}
#Override
public int hashCode() {
return id.hashCode();
}
}
WorkPhoneNumber
Based on your comment I have added a subclass of PhoneNumber.
package forum7587095;
public class WorkPhoneNumber extends PhoneNumber {
private String extension;
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
#Override
public boolean equals(Object arg0) {
if(!super.equals(arg0)) {
return false;
}
return equals(extension, ((WorkPhoneNumber) arg0).getExtension());
}
}
PhoneNumberAdapter
Below is the implementation of the XmlAdapter. Note that we must maintain if the PhoneNumber object has been seen before. If it has we only populate the id portion of the AdaptedPhoneNumber object.
package forum7587095;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class PhoneNumberAdapter extends XmlAdapter<PhoneNumberAdapter.AdaptedPhoneNumber, PhoneNumber>{
private List<PhoneNumber> phoneNumberList = new ArrayList<PhoneNumber>();
private Map<String, PhoneNumber> phoneNumberMap = new HashMap<String, PhoneNumber>();
#XmlSeeAlso(AdaptedWorkPhoneNumber.class)
#XmlType(name="phone-number")
public static class AdaptedPhoneNumber {
#XmlAttribute public String id;
public String number;
public AdaptedPhoneNumber() {
}
public AdaptedPhoneNumber(PhoneNumber phoneNumber) {
id = phoneNumber.getId();
number = phoneNumber.getNumber();
}
public PhoneNumber getPhoneNumber() {
PhoneNumber phoneNumber = new PhoneNumber();
phoneNumber.setId(id);
phoneNumber.setNumber(number);
return phoneNumber;
}
}
#XmlType(name="work-phone-number")
public static class AdaptedWorkPhoneNumber extends AdaptedPhoneNumber {
public String extension;
public AdaptedWorkPhoneNumber() {
}
public AdaptedWorkPhoneNumber(WorkPhoneNumber workPhoneNumber) {
super(workPhoneNumber);
extension = workPhoneNumber.getExtension();
}
#Override
public WorkPhoneNumber getPhoneNumber() {
WorkPhoneNumber phoneNumber = new WorkPhoneNumber();
phoneNumber.setId(id);
phoneNumber.setNumber(number);
phoneNumber.setExtension(extension);
return phoneNumber;
}
}
#Override
public AdaptedPhoneNumber marshal(PhoneNumber phoneNumber) throws Exception {
AdaptedPhoneNumber adaptedPhoneNumber;
if(phoneNumberList.contains(phoneNumber)) {
if(phoneNumber instanceof WorkPhoneNumber) {
adaptedPhoneNumber = new AdaptedWorkPhoneNumber();
} else {
adaptedPhoneNumber = new AdaptedPhoneNumber();
}
adaptedPhoneNumber.id = phoneNumber.getId();
} else {
if(phoneNumber instanceof WorkPhoneNumber) {
adaptedPhoneNumber = new AdaptedWorkPhoneNumber((WorkPhoneNumber)phoneNumber);
} else {
adaptedPhoneNumber = new AdaptedPhoneNumber(phoneNumber);
}
phoneNumberList.add(phoneNumber);
}
return adaptedPhoneNumber;
}
#Override
public PhoneNumber unmarshal(AdaptedPhoneNumber adaptedPhoneNumber) throws Exception {
PhoneNumber phoneNumber = phoneNumberMap.get(adaptedPhoneNumber.id);
if(null != phoneNumber) {
return phoneNumber;
}
phoneNumber = adaptedPhoneNumber.getPhoneNumber();
phoneNumberMap.put(phoneNumber.getId(), phoneNumber);
return phoneNumber;
}
}
Demo
To ensure the same instance of the XmlAdapter is used for the entire marshal and unmarshal operations we must specifically set an instance of the XmlAdapter on both the Marshaller and Unmarshaller:
package forum7587095;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setAdapter(new PhoneNumberAdapter());
File xml = new File("src/forum7587095/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
System.out.println(customer.getPhoneNumbers().get(0) == customer.getPhoneNumbers().get(2));
System.out.println(customer.getPhoneNumbers().get(3) == customer.getPhoneNumbers().get(4));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setAdapter(new PhoneNumberAdapter());
marshaller.marshal(customer, System.out);
}
}
Output
true
true
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<phone-number id="A">
<number>555-AAAA</number>
</phone-number>
<phone-number id="B">
<number>555-BBBB</number>
</phone-number>
<phone-number id="A"/>
<phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W">
<number>555-WORK</number>
<extension>1234</extension>
</phone-number>
<phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"/>
</customer>
For More Information
http://blog.bdoughan.com/2011/09/mixing-nesting-and-references-with.html
http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html
http://blog.bdoughan.com/search/label/XmlAdapter
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html
http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html

EclipseLink MOXy with recursive data structures / child elements of same type

I am using EclipseLink MOXy and have a data structure that has child elements of the same data type. Now I don't want to serialize the datastructure with infinite depth, but only the first level.
Here is some example code of the data structure:
package test;
import java.util.Collection;
import java.util.Vector;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement
public class MyClass {
private int id;
private String details;
private Collection<MyClass> children = new Vector<MyClass>();
public MyClass() {
}
public MyClass(int id, String details) {
this.id = id;
this.details = details;
}
#XmlElementWrapper
#XmlElementRef
public Collection<MyClass> getChildren() {
return children;
}
public void addChild(MyClass child) {
children.add(child);
}
public String getDetails() {
return details;
}
#XmlAttribute
public int getId() {
return id;
}
public void setChildren(Collection<MyClass> children) {
this.children = children;
}
public void setDetails(String details) {
this.details = details;
}
public void setId(int id) {
this.id = id;
}
}
And my test program:
package test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Test {
public static void main(String[] args) throws Exception {
MyClass l1 = new MyClass(1, "Level 1");
MyClass l2 = new MyClass(2, "Level 2");
l1.addChild(l2);
MyClass l3 = new MyClass(3, "Level 3");
l2.addChild(l3);
JAXBContext jc = JAXBContext.newInstance(MyClass.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(l1, System.out);
}
}
The following XML is generated:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myClass id="1">
<children>
<myClass id="2">
<children>
<myClass id="3">
<children/>
<details>Level 3</details>
</myClass>
</children>
<details>Level 2</details>
</myClass>
</children>
<details>Level 1</details>
</myClass>
However, I'd like the xml too look like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myClass id="1">
<children>
<myClass id="2">
<details>Level 2</details>
</myClass>
</children>
<details>Level 1</details>
</myClass>
Thanks.
To accomplish this use case we will leverage two concepts from JAXB: XmlAdapter and Marshaller.Listener.
MyClassAdapter
We will leverage the default JAXB behaviour of not marshalling an element for a null value. To do this we will implement an XmlAdapter that returns null after a specified level has been reached. To count the levels we will create a Marshaller.Listener.
package forum11769758;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MyClassAdapter extends XmlAdapter<MyClass, MyClass>{
private int levels;
private MyMarshallerListener marshallerListener;
public MyClassAdapter() {
}
public MyClassAdapter(int levels) {
this.levels = levels;
}
public Marshaller.Listener getMarshallerListener() {
if(null == marshallerListener) {
marshallerListener = new MyMarshallerListener();
}
return marshallerListener;
}
#Override
public MyClass marshal(MyClass myClass) throws Exception {
if(null == marshallerListener || marshallerListener.getLevel() < levels) {
return myClass;
}
return null;
}
#Override
public MyClass unmarshal(MyClass myClass) throws Exception {
return myClass;
}
static class MyMarshallerListener extends Marshaller.Listener {
private int level = 0;
public int getLevel() {
return level;
}
#Override
public void afterMarshal(Object object) {
if(object instanceof MyClass) {
level--;
}
}
#Override
public void beforeMarshal(Object object) {
if(object instanceof MyClass) {
level++;
}
}
}
}
MyClass
The #XmlJavaTypeAdapter annotation is used to specify that an XmlAdapter should be used.
package forum11769758;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement
public class MyClass {
private int id;
private String details;
private Collection<MyClass> children = new Vector<MyClass>();
public MyClass() {
}
public MyClass(int id, String details) {
this.id = id;
this.details = details;
}
#XmlElementWrapper
#XmlElementRef
#XmlJavaTypeAdapter(MyClassAdapter.class)
public Collection<MyClass> getChildren() {
return children;
}
public void addChild(MyClass child) {
children.add(child);
}
public String getDetails() {
return details;
}
#XmlAttribute
public int getId() {
return id;
}
public void setChildren(Collection<MyClass> children) {
this.children = children;
}
public void setDetails(String details) {
this.details = details;
}
public void setId(int id) {
this.id = id;
}
}
Test
Since we need to use the XmlAdapter in a stateful way, we will set an instance of it on the Marshaller, we will also set the instance of Marshaller.Listener we created on the Marshaller.
package forum11769758;
import javax.xml.bind.*;
public class Test {
public static void main(String[] args) throws Exception {
MyClass l1 = new MyClass(1, "Level 1");
MyClass l2 = new MyClass(2, "Level 2");
l1.addChild(l2);
MyClass l3 = new MyClass(3, "Level 3");
l2.addChild(l3);
JAXBContext jc = JAXBContext.newInstance(MyClass.class);
Marshaller marshaller = jc.createMarshaller();
MyClassAdapter myClassAdapter = new MyClassAdapter(2);
marshaller.setAdapter(myClassAdapter);
marshaller.setListener(myClassAdapter.getMarshallerListener());
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(l1, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8"?>
<myClass id="1">
<children>
<myClass id="2">
<children/>
<details>Level 2</details>
</myClass>
</children>
<details>Level 1</details>
</myClass>
For More Information
The following articles expand on the topics discussed in this answer:
http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html
http://blog.bdoughan.com/2011/09/mixing-nesting-and-references-with.html

Categories

Resources