bdo*_*han 11
注意: 我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员.
下面是一个如何使用MOXy的JSON绑定来支持这个用例的示例.
JAVA模型
下面是使用JAXB元数据注释的示例域模型.相同的元数据将用于对象到XML和对象到JSON的转换.
顾客
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
private int id;
private String firstName;
@XmlElement(nillable=true)
private String lastName;
private List<PhoneNumber> phoneNumbers;
}
Run Code Online (Sandbox Code Playgroud)
电话号码
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class PhoneNumber {
@XmlAttribute
private String type;
@XmlValue
private String number;
}
Run Code Online (Sandbox Code Playgroud)
XML INPUT
下面是我们将使用的XML输入.请注意如何在元素上xsi:nil使用该属性lastName来指示null值.还要注意phoneNumbers元素如何具有type属性.
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<id>123</id>
<firstName>Jane</firstName>
<lastName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<phoneNumbers type="work">555-1111</phoneNumbers>
</customer>
Run Code Online (Sandbox Code Playgroud)
演示代码
jaxb.properties
要将MOXy指定为JAXB提供程序,您需要jaxb.properties在与域模型相同的程序包中包含一个名为的文件,并带有以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as -your.html):
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Run Code Online (Sandbox Code Playgroud)
演示
以下演示代码将XML转换为域模型,然后再转换回JSON.
import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum14734741/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
marshaller.marshal(customer, System.out);
}
}
Run Code Online (Sandbox Code Playgroud)
JSON OUTPUT
请注意键的null值如何lastName表示为正确的JSON.还要注意type密钥如何不包含任何与XML表示中的XML属性相对应的特殊指示符.
{
"id" : 123,
"firstName" : "Jane",
"lastName" : null,
"phoneNumbers" : [ {
"type" : "work",
"value" : "555-1111"
} ]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28299 次 |
| 最近记录: |