Thursday, January 14, 2016

JAXB: Marshalling entity to String example

 Here is an example / template for marshalling entity to String:

 Marshalling code fragment

java.io.StringWriter sw = new StringWriter();

JAXBContext pContext = JAXBContext.newInstance(SomeEntity.class);

Marshaller marshaller = pContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(dto, sw);

sw.toString();

SomeEntity.java

@XmlRootElement(name = "result")
@XmlAccessorType(XmlAccessType.FIELD)
public class SomeEntity{
    private String someVar;
    private String someOtherVal;
    ...
    // getters & setters
}

No comments:

Post a Comment