@XmlRootElement
public class User {
private Long id;
private String firstName;
private String lastName;
private List<Address> addresses;
User class contains @XmlRootElement needed by JAXB
public class Address {
private String city;
private String county;
private String street;
Address class with 3 fields
User anUser = new User();
anUser.setId(1l);
anUser.setFirstName("MyFirstName");
anUser.setLastName("MyLastName");
anUser.setAddresses(Arrays.asList(new Address("London", "I have No ideea", "a street")));
now we have cretaed the objects which will be converted to xml
marshaller.marshal
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter stringWriter = new StringWriter();
marshaller.marshal(anUser,stringWriter);
System.out.println(stringWriter);
String writer now contains the xml :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<addresses>
<city>London</city>
<county>I have No ideea</county>
<street>a street</street>
</addresses>
<firstName>MyFirstName</firstName>
<id>1</id>
<lastName>MyLastName</lastName>
</user>
Unmarshaller.unmarshal
String theXml = JaxbMarshallExample.testMarshall();
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader stringReader = new StringReader(theXml);
User theUser = (User) jaxbUnmarshaller.unmarshal(stringReader);
System.out.println(theUser);
the output wil be :
User{id=1, firstName='MyFirstName', lastName='MyLastName', addresses=[Address{city='London', county='I have No ideea', street='a street'}]}
InputStream inputStream = new ByteArrayInputStream(theXml.getBytes());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
User theUserAgain = (User) jaxbUnmarshaller.unmarshal(inputStreamReader);
System.out.println(theUserAgain);
The output is the same.
Download Source Code
Category: Java Tutorials