注意: 我是 Eclipselink
JAXB(MOXy)的 负责人,并且是
JAXB(JSR-222) 专家组的成员。
如果杰克逊无法做到这一点,那么用例将适用于MOXy。
Java模型
oo
这是一个示例类,其中包含type字段
JAXBElement。
import javax.xml.bind.JAXBElement;import javax.xml.bind.annotation.*;@XmlAccessorType(XmlAccessType.FIELD)public class Foo { @XmlElementRef(name="bar") private JAXBElement<Bar> bar;}酒吧
public class Bar {}对象工厂
import javax.xml.bind.JAXBElement;import javax.xml.bind.annotation.*;import javax.xml.namespace.QName;@XmlRegistrypublic class ObjectFactory { @XmlElementDecl(name = "bar") public JAXBElement<Bar> createBar(Bar bar) { return new JAXBElement<Bar>(new QName("bar"), Bar.class, bar); }}独立演示代码
下面是一些可以在Java SE中运行的演示代码,以查看一切正常:
演示版
import java.util.*;import javax.xml.bind.*;import javax.xml.transform.stream.StreamSource;import org.eclipse.persistence.jaxb.JAXBContextProperties;public class Demo { public static void main(String[] args) throws Exception { Map<String, Object> properties = new HashMap<String, Object>(2); properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json"); properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false); JAXBContext jc = JAXBContext.newInstance(new Class[] {Foo.class, ObjectFactory.class}, properties); Unmarshaller unmarshaller = jc.createUnmarshaller(); StreamSource json = new StreamSource("src/forum19158056/input.json"); Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(foo, System.out); }}input.json /输出
{"bar" : {} }使用JAX-RS运行
以下链接将帮助您在JAX-RS服务中利用MOXy:
- http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
- http://blog.bdoughan.com/2013/06/moxy-is-new-default-json-binding.html



