现在我有了这堂课:
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和Google,这些答案都不起作用:
使用Eclipselink.media-type值设置封送器属性时的PropertyException:Application/JSON JAXB javax.xml.bind.PropertyException
您需要确保jaxb.properties
文件与用于引导jaxbcontext
的域类在同一个包中,并且EclipseLink MOXy位于类路径上。
如果您使用的是Maven,那么jaxb.properties
文件应该位于以下位置,假设foo
位于名为com.example.foo
的包中:
有关完整示例,请参阅: