由于您的 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>
发布组
下面是我将用于此示例的域模型。注意type
属性是如何用 注释的@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
要将 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
演示
由于 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"
}
}