注:我是EclipseLink JAXB (MOXy)鉛和JAXB (JSR-222)專家小組的成員。
由於您已經建立了JAXB映射並將XML轉換爲JSON,因此您可能會對使用相同JAXB元數據提供對象到XML和對象到JSON映射的EclipseLink JAXB(MOXy)感興趣。
客戶
下面是JAXB註釋的樣本模型。
package forum11599191;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlAttribute
private int id;
private String firstName;
@XmlElement(nillable=true)
private String lastName;
private List<String> email;
}
jaxb.properties
要在同一個包中使用莫西爲您的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
input.xml中
<?xml version="1.0" encoding="UTF-8"?>
<customer id="123" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<firstName>Jane</firstName>
<lastName xsi:nil="true"/>
<email>[email protected]</email>
</customer>
演示
下面演示代碼將填充從XML對象,然後輸出JSON。注意Moxy沒有編譯時間依賴性。
package forum11599191;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
// Unmarshal from XML
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11599191/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
// Marshal to JSON
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.marshal(customer, System.out);
}
}
JSON輸出繼電器
下面是從運行演示代碼的輸出。
{
"customer" : {
"id" : 123,
"firstName" : "Jane",
"lastName" : null,
"email" : [ "[email protected]" ]
}
}
有幾件事情需要注意的輸出:
- 由於
id
字段是數字型它編組到JSON沒有引號。
- 即使
id
字段已使用@XmlAttribute
進行映射,但在JSON消息中沒有特別說明。
email
屬性的大小爲List
,這在JSON輸出中正確表示。
xsi:nil
機制用於指定lastName
字段有一個null
值,這已被轉換爲JSON輸出中正確的空表示。
更多信息
他們是一個導出混合HashMap列表的好方法嗎?即HashMap –
kdgwill
2012-09-01 17:25:46