javax.xml.bind.PropertyException:name:eclipselink.media-type value:application / json

时间:2017-03-01 12:16:29

标签: java json spring jaxb

我正在使用Spring Framework制作一个项目,我想使用JaxB将对象转换为json,我收到了这个错误:

javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(Unknown Source)
at com.fabbydesign.controller.DashboardController.main(DashboardController.java:82)

我测试的代码是:

public static void main(String[] args) throws ParseException{

    ReturnBean rb = new ReturnBean();
    rb.setStatus(1);
    rb.setMessage("Message here!");

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(ReturnBean.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
        marshaller.marshal(rb, System.out);

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我在pom.xml中添加了EclipseLink依赖:

<dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.6.4</version>
    </dependency>

并且,我已将文件jaxb.properties添加了内容:

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

我不知道为什么我仍然接受这个错误,因为,正如我在这个论坛上看到的那样,我认为我做了所有。 我要提的是,我测试的代码在目录中:

src\main\java\com\fabbydesign\controller

,文件jaxb.properties位于目录中:

src\main\resources\com\fabbydesign\controller

我做错了什么?

3 个答案:

答案 0 :(得分:1)

我不确定jaxb.properties文件的位置是否正确。 stacktrace仍然包含com.sun.xml.internal.bind.v2.runtime类,它表示仍在使用错误的工厂类。

请点击此处查看有关设置工厂的更多信息或其他方式:Where to include jaxb.properties file?

答案 1 :(得分:1)

我发现了问题:我必须在ReturnBean类所在的包中添加jaxb.properties !!!

答案 2 :(得分:1)

简单,您可以指定系统变量,如:

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

它对我有用。

相关问题