线程“main”中的exceptionjavax.xml.bind.PropertyException:name:eclipselink.media-type value:application / json

我试图按照这里的示例,但得到一个javax.xml.bind.PropertyException。 由于以下代码行,我收到此exception:

marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); 

我已经完全复制/粘贴了上面列出的示例,因此我的代码正是您在那里看到的。 搜索SO和谷歌对此没什么帮助,并且认为我会把这些带给SO的天才以获得一些帮助。 任何帮助都会受到最高的赞赏,(de)使用JSON和XML与json.org,Jackson和JAXB进行序列化已经变成了一个消耗了近一个月生命的黑色和无底洞。

我的第一印象是我没有正确指定eclipselink运行时( 如此处所述 ),但没有产生解决方案。

堆栈跟踪:

 Exception in thread "main" javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(AbstractMarshallerImpl.java:358) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(MarshallerImpl.java:527) at HelloWorld.main(HelloWorld.java:17) 

这就是我正在做的事情,

在此处输入图像描述

您需要在类路径上安装EclipseLink jar(2.4.0或更高版本),并在与用于使用以下条目引导JAXBContext的类相同的包中使用jaxb.properties文件:

 javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

下面是一个关于GitHub示例的链接,您可以运行该示例来查看所有工作:

我添加的主要方法(你也可以使用-D ):

 System.setProperty("javax.xml.bind.context.factory","org.eclipse.persistence.jaxb.JAXBContextFactory"); 

如果您不想添加jaxb.properties文件,则可以使用Java代码完成所有操作。 这对于您不希望通过引入新的jaxb.properties文件而影响类路径的遗留系统特别有用。

 import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.JAXBContextProperties; import org.eclipse.persistence.jaxb.xmlmodel.ObjectFactory; //Set the various properties you want Map properties = new HashMap<>(); properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json"); properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false); //Create a Context using the properties JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] { MyClass.class, ObjectFactory.class}, properties); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Marshall the object StringWriter stringWriter = new StringWriter(); jaxbMarshaller.marshal(myObject, stringWriter); String json = stringWriter.toString();