gpt4 book ai didi

java - MOXy JAXB javax.xml.bind.PropertyException

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:58 25 4
gpt4 key购买 nike

我按照这个例子:http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JSON_Twitter

现在我有这个类:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.eclipse.persistence.jaxb.MarshallerProperties;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
unmarshaller.setProperty("eclipselink.json.include-root", false);
StreamSource source = new StreamSource("http://test.url/path/to/resource");
JAXBElement<Foo> jaxbElement = unmarshaller.unmarshal(source, Foo.class);

System.out.println(jaxbElement.getValue().getFoo());

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty("eclipselink.json.include-root", false);
marshaller.marshal(jaxbElement, System.out);
}
}

我有jaxb.properties:

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

如果我运行这段代码,我会得到:

Exception in thread "main" javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.setProperty(AbstractUnmarshallerImpl.java:352)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.setProperty(UnmarshallerImpl.java:450)
at com.example.JavaSEClient.main(JavaSEClient.java:19)

我该如何解决这个问题?

我搜索了 SO 和谷歌,这些答案不起作用:

PropertyException when setting Marshaller property with eclipselink.media-type value: application/json JAXB javax.xml.bind.PropertyException

最佳答案

您需要确保您的 jaxb.properties 文件与您用来引导 JAXBContext 的域类在同一个包中,并且 EclipseLink MOXy 已打开你的类(class)路径。

如果您使用的是 Maven,则 jaxb.properties 文件应位于以下位置,假设 Foo 在名为 com.example.Foo 的包中:

  • src/main/resources/com/example/foo/jaxb.properties
  • src/main/java/com/example/foo/Foo.class

有关完整示例,请参阅:

关于java - MOXy JAXB javax.xml.bind.PropertyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22839359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com