Java JAXB marshall unmarshall Examples from String and Stream

Now we will try to create an xml from java POJO and then recreate the java objects

1. creating java POJO classes 

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.setAddresses(Arrays.asList(new Address("London", "I have No ideea", "a street")));

now we have cretaed the objects which will be converted to xml

2. Transform to xml using JAXB marshaller.marshal

        JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        StringWriter stringWriter = new StringWriter();

String writer now contains the xml :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <county>I have No ideea</county>
 <street>a street</street>

2. Transform XML to java objects using 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);

the output wil be :

User{id=1, firstName='MyFirstName', lastName='MyLastName', addresses=[Address{city='London', county='I have No ideea', street='a street'}]}

2.1 Transform XML from InputStream

        InputStream inputStream = new ByteArrayInputStream(theXml.getBytes());
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        User theUserAgain = (User) jaxbUnmarshaller.unmarshal(inputStreamReader);

The output is the same.

Download Source Code

Category: Java Tutorials