Note. I am an EclipseLink JAXB (MOXy) and a member of the JAXB Group (JSR-222) .
The following is an example of how this can be done using MOXy using the @XmlPath extension.
Person
package forum7652387; import javax.xml.bind.annotation.*; import org.eclipse.persistence.oxm.annotations.XmlPath; @XmlAccessorType(XmlAccessType.FIELD) public class Person { String name; @XmlPath(".") Address homeAddress; }
Address
package forum7652387; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Address { @XmlElement(name="homeAddress_street") String street; @XmlElement(name="homeAddress_zip") String zip; }
jaxb.properties
To specify MOXy as the JAXB provider, you need to add a file named jaxb.properties in the same package as the domain classes, with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
package forum7652387; import java.io.StringReader; import javax.xml.bind.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Person.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setProperty("eclipselink.media-type", "application/json"); unmarshaller.setProperty("eclipselink.json.include-root", false); String jsonString = "{\"name\":\"John\", \"homeAddress_street\":\"123 Street\", \"homeAddress_zip\":\"xxxxx\"}"; StreamSource jsonSource = new StreamSource(new StringReader(jsonString)); Person person = unmarshaller.unmarshal(jsonSource, Person.class).getValue(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty("eclipselink.media-type", "application/json"); marshaller.setProperty("eclipselink.json.include-root", false); marshaller.marshal(person, System.out); } }
Output
{"name" : "John", "homeAddress_street" : "123 Street", "homeAddress_zip" : "xxxxx"}
Additional Information
source share