Saturday, February 26, 2011

Quick Java code to convert a Java object into XML

I keep having to do it and I keep forgetting...

private static String objectToXML(Object object, Class clazz) throws JAXBException,
 PropertyException {

 JAXBContext jc = JAXBContext.newInstance(clazz);
 Marshaller marshaller = jc.createMarshaller();
 marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
 ByteArrayOutputStream baos = new ByteArrayOutputStream();   
 marshaller.marshal(object, baos);
 return new String(baos.toByteArray());
}
 



This is another working example (courtesy of Adam Bien):



import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Duke {
 private String language;
 private int age;
 
 
 @Override
 public String toString() {
  return "Duke [language=" + language + ", age=" + age + "]";
 }

 public Duke(String language, int age) {
  super();
  this.language = language;
  this.age = age;
 }
 
 public Duke() {
  
 }
 
}





import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.junit.jupiter.api.Test;

public class DukeTest {
 @Test
 public void testSerialization() throws JAXBException {
  JAXBContext context = JAXBContext.newInstance(Duke.class);
  Marshaller marshaller = context.createMarshaller();
  marshaller.marshal(new Duke("Java", 2), new File("duke.xml"));
  Unmarshaller unmarshaller = context.createUnmarshaller();
  Object unmarshalled = unmarshaller.unmarshal(new File("duke.xml"));
  System.out.println(unmarshalled);
 }
}



No comments: