目前,我在解码我自己编码的 XML 时遇到了一些问题。我花了一些时间才弄清楚,因为我认为编码进行得很顺利(没有异常(exception)等)。生成 XML 的方法返回:
<?xml version="1.0" encoding="UTF-8"?> version="1.0" encoding="UTF-8" standalone="yes"
<TestClass>
<testValue>banaan</testValue>
</TestClass>
但是突然我有了一个非常明显的认识(太晚了),生成的 XML 根本不正确。显然应该是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TestClass>
<testValue>banaan</testValue>
</TestClass>
这个非常简单的代码怎么可能:
@Path("test")
@GET
@Produces(MediaType.APPLICATION_XML)
public TestClass getTestClass() {
TestClass test = new TestClass();
test.setTestValue("banaan");
return test;
}
和测试类:
@XmlRootElement(name = "TestClass")
public class TestClass {
private String testValue;
@XmlElement(name = "testValue")
public String getTestValue() {
return testValue;
}
public void setTestValue(String testValue) {
this.testValue = testValue;
}
public TestClass() {
}
}
生成无效的 XML?更重要的是,我该如何解决它?
最佳答案
您正在使用默认尝试创建一个应该正常运行的 JAXBContext,但它似乎以某种方式搞砸了。尝试向您的应用程序添加自定义上下文解析器。
@Provider
public class XmlContextProvider implements ContextResolver<JAXBContext> {
private JAXBContext context = null;
public JAXBContext getContext(Class<?> type) {
if (type != TestClass.class) {
return null; // we don't support nothing else than TestClass
}
if (context == null) {
try {
context = JAXBContext.newInstance(TestClass.class);
} catch (JAXBException e) {
e.printStackTrace();
}
}
return context;
}
}
您还必须将 XmlContextProvider 添加到您的 Application 类中。
关于java - 生成 XML 时 JAX-RS 的奇怪响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20481657/