【问题标题】:javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/jsonjavax.xml.bind.PropertyException:名称:eclipselink.media-type 值:应用程序/json
【发布时间】:2017-07-20 18:22:51
【问题描述】:

我在一个项目中工作,使用 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

我做错了什么?

【问题讨论】:

    标签: java json spring jaxb


    【解决方案1】:

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

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

    它对我有用。

    【讨论】:

      【解决方案2】:

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

      在此处查看更多信息或设置工厂的替代方法:Where to include jaxb.properties file?

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 这就是我上面回答的意思。 jaxb.properties 的位置错误。很好,你已经解决了!
        猜你喜欢
        • 2014-01-24
        • 1970-01-01
        • 2014-02-12
        • 1970-01-01
        • 2017-01-15
        • 2021-09-21
        • 2015-07-24
        • 2017-06-18
        • 1970-01-01
        相关资源
        最近更新 更多