我尝试按照位于here的示例操作,但得到了一个javax.xml.bind.PropertyException。我收到此异常是因为下面这行代码:
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
我已经从字面上复制/粘贴了上面列出的示例,所以我的代码与您在那里看到的完全相同。在SO和Google上搜索这个并没有什么帮助,我想我应该把这个带给SO的天才们来寻求一些帮助。任何帮助都将不胜感激,json.org、Jackson和JAXB对JSON和XML的(反)序列化已经变成了一个黑色的无底洞,几乎耗费了我一个月的时间。
我的第一印象是我没有正确地指定eclipselink运行时(as described here),但这并没有产生解决方案。
堆栈跟踪:
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)
这就是我要做的
发布于 2016-02-10 02:16:52
在我的main方法中添加了(你也可以使用-D
):
System.setProperty("javax.xml.bind.context.factory","org.eclipse.persistence.jaxb.JAXBContextFactory");
发布于 2017-05-31 03:28:47
如果不想添加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<String, Object> 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();
https://stackoverflow.com/questions/20962053
复制相似问题