Skip to content

Instantly share code, notes, and snippets.

@golonzovsky
Last active September 9, 2019 11:59
Show Gist options
  • Save golonzovsky/5539763 to your computer and use it in GitHub Desktop.
Save golonzovsky/5539763 to your computer and use it in GitHub Desktop.
jaxb wrapper example for non-list elements
package com.test.ws;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class JaxbTest {
public static void main(String[] args) throws JAXBException {
final ExampleObject obj = new ExampleObject();
obj.setObj1(new InnerObject("id1", "code1"));
obj.setObj2(new InnerObject("id2", "code2"));
final Marshaller marshaller = JAXBContext.newInstance(ExampleObject.class).createMarshaller();
marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
marshaller.marshal(obj, System.out);
}
}
@XmlRootElement
class ExampleObject{
private InnerObject obj1;
private InnerObject obj2;
@XmlTransient
public InnerObject getObj1() {
return obj1;
}
public void setObj1(InnerObject obj1) {
this.obj1 = obj1;
}
@XmlTransient
public InnerObject getObj2() {
return obj2;
}
public void setObj2(InnerObject obj2) {
this.obj2 = obj2;
}
private static class EntityWrapper {
@XmlElement(name = "company")
private InnerObject entity;
EntityWrapper() { }
private EntityWrapper(InnerObject entity) {
this.entity = entity;
}
public InnerObject getEntity() {
return entity;
}
}
@XmlElement(name = "agent")
private void setEntity1(EntityWrapper entityWrapper) {
obj1 = entityWrapper.getEntity();
}
@XmlElement(name = "office")
private void setEntity2(EntityWrapper entityWrapper) {
obj2 = entityWrapper.getEntity();
}
private EntityWrapper getEntity1(){
return new EntityWrapper(obj1);
}
private EntityWrapper getEntity2(){
return new EntityWrapper(obj2);
}
}
@XmlAccessorType(XmlAccessType.FIELD)
class InnerObject{
private String id;
private String code;
InnerObject(String id, String code) {
this.id = id;
this.code = code;
}
}
@golonzovsky
Copy link
Author

result:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<exampleObject>
    <agent>
        <company>
            <id>id1</id>
            <code>code1</code>
        </company>
    </agent>
    <office>
        <company>
            <id>id2</id>
            <code>code2</code>
        </company>
    </office>
</exampleObject>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment