注意:我是
EclipseLink JAXB (MOXy)的负责人和
JAXB (JSR-222)专家组成员。
以下是使用MOXy的@XmlPath
扩展来完成此操作的示例。
人员信息
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;
}
地址
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
为了将MOXy作为您的JAXB提供程序,您需要在与域类相同的包中添加一个名为jaxb.properties
的文件,并添加以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
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);
}
}
输出
{"name" : "John", "homeAddress_street" : "123 Street", "homeAddress_zip" : "xxxxx"}
了解更多信息