由於您的JSON綁定與XML綁定稍有不同,因此我會使用EclipseLink JAXB (MOXy)的外部映射文件。
oxm.xml
在外部映射文件中,我們將迎來type
領域作爲暫時的。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum383861">
<java-types>
<java-type name="ReleaseGroup">
<java-attributes>
<xml-transient java-attribute="type"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
ReleaseGroup
下面是我會用這個例子的域模型。請注意0屬性是如何用@XmlAttribute
進行註釋的。
package forum383861;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="release-group")
@XmlAccessorType(XmlAccessType.FIELD)
public class ReleaseGroup {
@XmlAttribute
String type;
String title;
}
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
演示
由於XML和JSON表示是不同的,我們會爲他們創建單獨的JAXBContexts
。對於JSON,我們將利用MOXy的外部映射文件。
package forum383861;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
ReleaseGroup rg = new ReleaseGroup();
rg.type = "Album";
rg.title = "Fred";
// XML
JAXBContext xmlJC = JAXBContext.newInstance(ReleaseGroup.class);
Marshaller xmlMarshaller = xmlJC.createMarshaller();
xmlMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
xmlMarshaller.marshal(rg, System.out);
// JSON
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum383861/oxm.xml");
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
JAXBContext jsonJC = JAXBContext.newInstance(new Class[] {ReleaseGroup.class}, properties);
Marshaller jsonMarshaller = jsonJC.createMarshaller();
jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jsonMarshaller.marshal(rg, System.out);
}
}
輸出
下面是從運行演示代碼的輸出:
<?xml version="1.0" encoding="UTF-8"?>
<release-group type="Album">
<title>Fred</title>
</release-group>
{
"release-group" : {
"title" : "Fred"
}
}
感謝的伎倆 – 2012-07-17 20:30:54
BTW @Blaise Doughan您的答覆是太棒了,但伊夫看了看現場的EclipseLink並找不到任何記錄在這裏的信息,是嗎? – 2012-07-18 08:37:52