Exception in thread “main” javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json

匆匆过客 提交于 2019-12-03 22:38:27

You need to have the EclipseLink jars (2.4.0 or newer) on your class path, and a jaxb.properties file in the same package as the classes used to bootstrap theJAXBContext with the following entry:

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

Below is a link to an example on GitHub that you can run to see everything working:

weller1

To my main method I added (you could also use -D):

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

If you don't want to add a jaxb.properties file, you can do this all in Java code. This is especially helpful for legacy systems where you don't want to risk affecting the classpath by introducing a new jaxb.properties file.

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!