Last active
September 9, 2019 11:59
-
-
Save golonzovsky/5539763 to your computer and use it in GitHub Desktop.
jaxb wrapper example for non-list elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
result: