- Part I - Basic Annotations, Inheritance
- Part II - JAXB Context, Generics
- Part III - Can't Handle Interfaces
- Part IV - XmlAdapter, Map, Special Types Annotations
Tips & Tricks, Summaries, Check Lists, Do's & Don'ts, Reminders, Stuff that works...
Showing posts with label JAXB. Show all posts
Showing posts with label JAXB. Show all posts
Thursday, 23 August 2012
JAXB Annotations Tutorial with Code Examples
This post regroups a set of JAXB annotation 'tutorial' posts. Consider it a table of content:
Thursday, 9 August 2012
JAXB Annotation - XmlAdapter, Map, Special Types Annotations
Code examples are available from Github in the JAXB-JSON-XML-Marshalling directory.
We are going to illustrate this with an example. Assuming an object containing a generic map:
We are going to need an adaptor:
Basically, the above adaptor converts a map into a list of entries (with key and value) when marshalling, and converts this list of entries back into a HashMap when unmarshalling.
The map-to-list and corresponding entries are:
Assuming one instantiates the object with generic map with destination and transports:
The generated XML and verification is:
To annotate an enum:
To specify the xml tag value and attributes:
For remaining annotations and usage of the above:
The generated XML and verification is:
JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
How to use XmlAdapter and @XmlJavaTypeAdapter to handle Map in JAXB?
In situations where JAXB cannot handle unknown types, the solution is to create an XmlAdapter and use the @XmlJavaTypeAdapter in the class referring to the unknown type to indicate JAXB how to deal with it. A Java map is a good example.We are going to illustrate this with an example. Assuming an object containing a generic map:
@XmlRootElement public class ObjectWithGenericMap<K, V> { private Map<K,V> map; @XmlElement @XmlJavaTypeAdapter(JaxbMapAdaptor.class) public Map<K,V> getMap() { return map; } public void setMap(Map<K,V> map) { this.map = map; } }
public class JaxbMapAdaptor<K, V> extends XmlAdapter<JaxbMapToList<K, V>, Map<K, V>> { @Override public Map<K, V> unmarshal(JaxbMapToList<K, V> v) throws Exception { HashMap<K, V> result = new HashMap<K, V>(); for (JaxbMapToListEntry<K, V> jme : v.getList()) { result.put(jme.getKey(), jme.getValue()); } return result; } @Override public JaxbMapToList marshal(Map<K, V> v) throws Exception { JaxbMapToList<K, V> result = new JaxbMapToList<K, V>(); for (Map.Entry<K, V> entry : v.entrySet()) { JaxbMapToListEntry<K, V> jme = new JaxbMapToListEntry<K, V>(); jme.setKey(entry.getKey()); jme.setValue(entry.getValue()); result.getList().add(jme); } return result; } }
Basically, the above adaptor converts a map into a list of entries (with key and value) when marshalling, and converts this list of entries back into a HashMap when unmarshalling.
The map-to-list and corresponding entries are:
public class JaxbMapToList <K, V> { private List<JaxbMapToListEntry<K, V>> list = new ArrayList<JaxbMapToListEntry<K, V>>(); public JaxbMapToList() {} public JaxbMapToList(Map<K, V> map) { for (Map.Entry<K, V> e : map.entrySet()) { list.add(new JaxbMapToListEntry<K, V>(e)); } } public List<JaxbMapToListEntry<K, V>> getList() { return list; } public void setList(List<JaxbMapToListEntry<K, V>> entry) { this.list = entry; } } public class JaxbMapToListEntry<K, V> { private K key; private V value; public JaxbMapToListEntry() { } public JaxbMapToListEntry(Map.Entry<K, V> e) { key = e.getKey(); value = e.getValue(); } @XmlElement public K getKey() { return key; } public void setKey(K key) { this.key = key; } @XmlElement public V getValue() { return value; } public void setValue(V value) { this.value = value; } }
@XmlRootElement public class Destination { private String destination; public String getDestination() { return destination; } @XmlElement public void setDestination(String dest) { this.destination = dest; } } @XmlRootElement public class Transport { private String transport; public String getTransport() { return transport; } @XmlElement public void setTransport(String transp) { this.transport = transp; } } public static void main(String[] args) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance( ObjectWithGenericMap.class, Destination.class, Transport.class); ObjectWithGenericMap<Destination,Transport> owgm = new ObjectWithGenericMap<Destination,Transport>(); Map<Destination,Transport> map = new HashMap<Destination,Transport>(); owgm.setMap(map); Destination d = new Destination(); d.setDestination("Paris"); Transport t = new Transport(); t.setTransport("Plane"); map.put(d,t); d = new Destination(); d.setDestination("New-York"); t = new Transport(); t.setTransport("Boat"); map.put(d,t); ObjectWithGenericMap<Destination,Transport> retr = marshallingUnmarshalling(jaxbContext, owgm); for (Entry<Destination, Transport> e : retr.getMap().entrySet() ){ Destination retrd = e.getKey(); System.out.print(retrd.getDestination()); Transport retrt = e.getValue(); System.out.println(" " + retrt.getTransport()); } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <objectWithGenericMap> <map> <list> <key xsi:type="destination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <destination>New-York</destination> </key> <value xsi:type="transport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <transport>Boat</transport> </value> </list> <list> <key xsi:type="destination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <destination>Paris</destination> </key> <value xsi:type="transport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <transport>Plane</transport> </value> </list> </map> </objectWithGenericMap>
Paris Plane New-York Boat
How to use: @XmlList, @XmlEnum, @XmlAttribute, @XmlValue, @XmlMimeType, @XmlInlineBinaryData?
To annotate an enum:
@XmlEnum public enum MyEnum { @XmlEnumValue("v1") VAL_1, @XmlEnumValue("v2") VAL_2; }
@XmlAccessorType(XmlAccessType.FIELD) public class SpecialItem { @XmlValue private String val; @XmlAttribute private String attribute1; @XmlAttribute private String attribute2; // Setter & Getters... }
@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class MultipleTypes { @XmlElement private MyEnum myEnum; @XmlElement @XmlList private List<String> data; @XmlElement private List<SpecialItem> specialItems; @XmlMimeType("image/jpeg") private Image image; @XmlInlineBinaryData private byte[] byteArray; // Setter & Getters... }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <multipleTypes> <myEnum>v2</myEnum> <data>tre pml xng</data> <specialItems attribute2="ffff" attribute1="aaaa">pppp</specialItems> <specialItems attribute2="pqgd" attribute1="mer">xxw</specialItems> <image>/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAALABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwCxBe6S1ha3ptg4MEYF29lGSXKA5JIznHvmuX1UaCmhapbwxW2023mxkWUSyedsbjPXaOTkdPX+9wieM/EEOlrpkeoEWS7SIfKQj5Rgfw88AflUb+JdVl0O7tHniMMkqbh9njDcq4Pzbcjj0PrXppRo3SuTVqVKrV7aH//Z</image> <byteArray>AQL9/A==</byteArray> </multipleTypes>
pppp aaaa ffff xxw mer pqgd VAL_2 tre, pml, xng, 1 2 -3 -4 Image is available: true
Remark
We have not covered all JAXB annotations, especially those related to XML schemas, but this tutorial should be enough to get one started and accomplish most objectives with JXTA.JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Labels:
Advanced,
Annotation,
Example,
Introduction,
JAXB,
JSON,
Reminder,
Summary,
Tutorial
Tuesday, 7 August 2012
JAXB Annotation - Can't Handle Interfaces
JAXB Can't Handle Interfaces in Generics
If you have a class with a List<Vehicle> and Vehicle is an interface, JAXB will throw an Exception at runtime:my.package.MyInterface is an interface, and JAXB can't handle interfaces
public abstract class Vehicle { public abstract String getType(); } @XmlRootElement public class Bus extends Vehicle { private String type; public Bus() { }; public Bus(String type) { this.type = type; } @XmlElement @Override public String getType() { return type; } public void setType(String type) { this.type = type; } } @XmlRootElement public class Car extends Vehicle { private String type; public Car() {}; public Car(String type) { this.type = type; } @XmlElement @Override public String getType() { return type; } public void setType(String type) { this.type = type; } } @XmlRootElement public class ObjectWithListOfVehicles { private List<Vehicle> list; @XmlElementWrapper(name="MyVehicleList") @XmlElement public List<Vehicle> getList() { return list; } public void setList(List<Vehicle> list) { this.list = list; } }
public static void interfaceExamples() throws JAXBException { List<Vehicle> l = new ArrayList<Vehicle>(); l.add(new Bus("Large bus")); l.add(new Bus("Small bus")); l.add(new Car("Ferrari")); // Object with generic list ObjectWithListOfVehicles owgl = new ObjectWithListOfVehicles(); owgl.setList(l); JAXBContext jc = JAXBContext.newInstance( Bus.class, Car.class, ObjectWithListOfVehicles.class); ObjectWithListOfVehicles retr = marshallUnmarshall(owgl, jc); for (Vehicle s : retr.getList()) { System.out.println( s.getClass().getSimpleName() + " - " + s.getType()); } System.out.println(" "); } public static <O> O marshallUnmarshall(O o, JAXBContext jc) throws JAXBException { // Creating a Marshaller Marshaller jaxbMarshaller = jc.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter result = new StringWriter(); jaxbMarshaller.marshal(o, result); // Printing XML String xml = result.toString(); System.out.println(xml); // Creating an Unmarshaller Unmarshaller jaxbUnmarshaller = jc.createUnmarshaller(); StringReader sr = new StringReader(xml); O retr = (O) jaxbUnmarshaller.unmarshal(sr); return retr; }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <objectWithListOfVehicles> <MyVehicleList> <list xsi:type="bus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <type>Large bus</type> </list> <list xsi:type="bus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <type>Small bus</type> </list> <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <type>Ferrari</type> </list> </MyVehicleList> </objectWithListOfVehicles> Bus - Large bus Bus - Small bus Car - Ferrari
Notice that JAXB is capable of recreating both Bus and Car instances.
Next
JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Labels:
Advanced,
Annotation,
Example,
Interface,
Introduction,
JAXB,
JSON,
Reminder,
Summary,
Tutorial
JAXB Annotation - JAXB Context, Generics
Understanding JAXB Context
In order to marshall and unmarshall JAXB annotated classes, one needs to create a JAXBContext. The instantiator method takes in a list of JAXB annotated Class.By default, JAXB will include statically referenced classes in the list and inherited classes, but not transient or inheriting classes. The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory.
Assuming:
@XmlRootElement public class StaticallyReferenced { private String data; @XmlElement public String getData() { return data; } public void setData(String data) { this.data = data; } } @XmlRootElement public class StaticallyReferencedButTransient { private String data; @XmlElement public String getData() { return data; } public void setData(String data) { this.data = data; } } @XmlRootElement public class SomeA { private StaticallyReferenced sr; private StaticallyReferencedButTransient srbt; @XmlElement public StaticallyReferenced getSr() { return sr; } public void setSr(StaticallyReferenced sr) { this.sr = sr; } @XmlTransient public StaticallyReferencedButTransient getSrbt() { return srbt; } public void setSrbt( StaticallyReferencedButTransient srbt) { this.srbt = srbt; } } @XmlRootElement public class InheritSomeA extends SomeA { private String moreData; @XmlElement public String getMoreData() { return moreData; } public void setMoreData(String moreData) { this.moreData = moreData; } }
JAXBContext jaxbContext = JAXBContext.newInstance(SomeA.class);
How to use JAXB with Generics such as List, Set, etc...?
Assuming a simple example, where an object contains a List<String>:@XmlRootElement public class ObjectWithList { private List<String> list; @XmlElementWrapper(name="MyList") @XmlElement public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } }
public static void simpleExample() throws JAXBException { List<String> l = new ArrayList<String>(); l.add("Somewhere"); l.add("This and that"); l.add("Something"); // Object with list ObjectWithList owl = new ObjectWithList(); owl.setList(l); JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class); ObjectWithList retr = marshallUnmarshall(owl, jc); for (String s : retr.getList()) { System.out.println(s); } System.out.println(" "); }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <objectWithList> <MyList> <list>Somewhere</list> <list>This and that</list> <list>Something</list> </MyList> </objectWithList> Somewhere This and that Something
@XmlRootElement public class ObjectWithGenericList<T> { private List<T> myList; @XmlElementWrapper(name="MyGenericList") @XmlElement public List<T> getList() { return myList; } public void setList(List<T> list) { this.myList = list; } }
public static void genericListExample() throws JAXBException { List<Car> l = new ArrayList<Car>(); l.add(new Car("red car")); l.add(new Car("blue car")); l.add(new Car("green car")); // Object with generic list ObjectWithGenericList<Car> owgl = new ObjectWithGenericList<Car>(); owgl.setList(l); JAXBContext jc = JAXBContext.newInstance( ObjectWithGenericList.class, Car.class); ObjectWithGenericList<Car> retr = marshallUnmarshall(owgl, jc); for (Car s : retr.getList()) { System.out.println( s.getClass().getSimpleName() + " - " + s.getType()); } System.out.println(" "); }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <objectWithGenericList> <MyGenericList> <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <type>red car</type> </list> <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <type>blue car</type> </list> <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <type>green car</type> </list> </MyGenericList> </objectWithGenericList> Car - red car Car - blue car Car - green car
Next
JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Labels:
Advanced,
Annotation,
Example,
Introduction,
JAXB,
JSON,
Reminder,
Summary,
Tutorial
Monday, 6 August 2012
JAXB Annotation - Basic Annotations, Inheritance
JAXB (Java Architecture for XML Binding) enables the mapping of Java object into XML documents back and forth. This post is an introduction, tutorial and summary of JAXB annotations. It proceeds with operational code examples to describe each feature.
The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory. Most examples rely on the following piece of code to create XML files from annotated Java objects:
In order to generate such XML documents, a JAXB context must be created. More details on this in part II.
This annotation can be used on a Class or on an enum. A Class does need a no parameter constructor or a factory method (more details in the @XmlType section).
For example:
generates the following XML:
One can also specify a namespace name for the XML element or a local name for the XML element.
The generated XML is:
If you need to exclude a field from the generated XML, use the @XmlTransient annotation.
Assuming the following class creation:
generates:
One can also set a default string value, or set the XML Schema element name and the target namespace of the XML element via the @XmlElement annotation.
The factory class:
The generated XML:
One can also set the XML Schema type and the target namespace of the XML Schema type with the @XmlType annotation.
This is best described with an example:
The generated output:
Next
JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory. Most examples rely on the following piece of code to create XML files from annotated Java objects:
public static void createXML(Object o) throws JAXBException { // Creating a Marshaller JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter result = new StringWriter(); jaxbMarshaller.marshal(o, result); // Printing XML String xml = result.toString(); System.out.println(xml); }
@XmlRootElement
Defines the root element of the XML document. If not name is specified (like this for example: @XmlRootElement(name = "MyRootName"), the name of the element is taken from the class name.This annotation can be used on a Class or on an enum. A Class does need a no parameter constructor or a factory method (more details in the @XmlType section).
For example:
@XmlRootElement(name="MyRootName") public class A { private int a1 = 0; @XmlElement public int getA1() { return a1; } public void setA1(int a1) { this.a1 = a1; } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <MyRootName> <a1>28</a1> </MyRootName>
Inheritance
When a class inherits of another annotated class, the root name is taken from the inheriting class:@XmlRootElement public class InheritsA extends A { private int b1 = 0; @XmlElement public int getB1() { return b1; } public void setB1(int b1) { this.b1 = b1; } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <inheritsA> <a1>33</a1> <b1>66</b1> </inheritsA>
@XmlElement / @XmlTransient
The @XmlElement indicates which element should be included in the XML conversion. If you want to annotate fields instead of getter methods, use the @XmlAccessorType(XmlAccessType.FIELD).If you need to exclude a field from the generated XML, use the @XmlTransient annotation.
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class FieldAnnotation { @XmlElement private int a1 = 45; @XmlTransient private long a2 = 0; @XmlElement(nillable=true) private String xxx = null; @XmlElement(required=true) private String req; public int getA1() { return a1; } public void setA1(int a1) { this.a1 = a1; } public long getA2() { return a2; } public void setA2(long a2) { this.a2 = a2; } public String getXxx() { return xxx; } public void setXxx(String xxx) { this.xxx = xxx; } public String getReq() { return req; } public void setReq(String req) { this.req = req; } }
FieldAnnotation fa = new FieldAnnotation(); fa.setA2(28); fa.setReq("Some value");
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <fieldAnnotation> <a1>45</a1> <xxx xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> <req>Some value</req> </fieldAnnotation>
@XmlType
This annotation allows one to specify the order of items in the generated XML document. It can also be used to specify a factory class and/or a factory method (with no arguments) to create instances of the annotated class:@XmlRootElement @XmlType(propOrder={"a2", "a1"}, factoryClass=OrderFactory.class, factoryMethod="myConstructor") public class Order { private int a1 = 0; private int a2 = 0; @XmlElement public int getA1() { return a1; } public void setA1(int a1) { this.a1 = a1; } @XmlElement public int getA2() { return a2; } public void setA2(int a2) { this.a2 = a2; } }
public class OrderFactory { public static Order myConstructor() { return new Order(); } }
<order> <a2>99</a2> <a1>28</a1> </order>
@XmlSeeAlso
This annotation allows one to refer to other classes to include in the XML generation. In other words, if a referred class is not in the JAXB context, it will be taken into account anyway and won't trigger a runtime error. This annotation can be used as a safeguard when marshalling and unmarshalling.This is best described with an example:
@XmlRootElement public class Document { private String content = ""; @XmlElement public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
@XmlRootElement public class Image { private String name = ""; @XmlElement public String getName() { return name; } public void setName(String content) { this.name = content; } }
@XmlRootElement @XmlSeeAlso({Document.class,Image.class}) public class Folder { private Document document = null; private Image image = null; @XmlElement public Document getDocument() { return document; } public void setDocument(Document document) { this.document = document; } @XmlElement public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <folder> <document> <content>My content</content> </document> <image> <name>My image</name> </image> </folder>
Next
JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Labels:
Annotation,
Crash Course,
Example,
Introduction,
JAXB,
JSON,
Reminder,
Summary,
Tutorial
Sunday, 5 August 2012
JAXB JSON Marshalling / Unmarshalling
The Jackson library offers a library to process objects with JAXB annotations, but it Jackson does not support all JAXB annotations (see the bottom of this page for more information).
The code example uses the following Java class:
We deliberately annotate the title as transient to prove that Jackson processes JAXB annotations and does not rely on the standard Pojo to JSON processus.
The following code performs the marshalling / unmarshalling:
It relies on the following dependency:
And produces the following:
Pojo to XML • Pojo to JSON • JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
The code example uses the following Java class:
@XmlRootElement() public class Recipe { private String title; private int duration; public String getTitle() { return title; } @XmlTransient public void setTitle(String title) { this.title = title; } public int getDuration() { return duration; } @XmlElement public void setDuration(int duration) { this.duration = duration; } }
The following code performs the marshalling / unmarshalling:
Recipe recipe = new Recipe(); recipe.setDuration(30); recipe.setTitle("Chicken recipe"); ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); mapper.setAnnotationIntrospector(introspector); // Printing JSON String result = mapper.writeValueAsString(recipe); System.out.println(result); // Parsing JSON Recipe retr = mapper.readValue(result, Recipe.class); System.out.println("Title : " + retr.getTitle()); System.out.println("Duration: " + retr.getDuration());
<dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>2.0.5</version> </dependency>
{"duration":30} Title : null Duration: 30
Pojo to XML • Pojo to JSON • JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Labels:
Example,
How To,
Java,
JAXB,
JSON,
Marshalling,
Tutorial,
Unmarshalling
JAXB XML Marshalling / Unmarshalling
We are going to perform a simple round trip to convert an JAXB annotated Java object into an XML (marshalling) and back into an XML object (unmarshalling). The code example is available on GitHub in the JAXB-JSON-XML Marshalling directory.
The following is a simple Java object with JAXB annotation:
The following code performs the round trip:
The output is:
Pojo to XML • Pojo to JSON • JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
The following is a simple Java object with JAXB annotation:
@XmlRootElement public class Book { private String title; private int year; public String getTitle() { return title; } @XmlElement public void setTitle(String title) { this.title = title; } public int getYear() { return year; } @XmlElement public void setYear(int year) { this.year = year; } }
public static void main(String[] args) throws JAXBException { Book book = new Book(); book.setTitle("Book title"); book.setYear(2010); // Creating a Marshaller JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter result = new StringWriter(); jaxbMarshaller.marshal(book, result); // Printing XML String xml = result.toString(); System.out.println(xml); // Creating an Unmarshaller Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); StringReader sr = new StringReader(xml); Book retr = (Book) jaxbUnmarshaller.unmarshal(sr); System.out.println("Title: " + retr.getTitle()); System.out.println("Year : " + retr.getYear()); }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <book> <title>Book title</title> <year>2010</year> </book> Title: Book title Year : 2010
Pojo to XML • Pojo to JSON • JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Labels:
Example,
How To,
Java,
JAXB,
JSON,
Marshalling,
Tutorial,
Unmarshalling,
XML
Subscribe to:
Posts (Atom)