Java JAXB使用jersey解组失败
我有一个表示POJO对象的类Java JAXB使用jersey解组失败,java,xml,jaxb,jersey,jax-rs,Java,Xml,Jaxb,Jersey,Jax Rs,我有一个表示POJO对象的类 import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; // Class to marshall and unmarshall the XML to POJO // This is a class for the request XML @XmlRootElement public class KeyProvision {
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
// Class to marshall and unmarshall the XML to POJO
// This is a class for the request XML
@XmlRootElement
public class KeyProvision {
private String Consumer ;
private String API ;
private String AllowedNames ;
public void setConsumer( String Consumer)
{
this.Consumer= Consumer;
}
public void setAPI( String API){
this.API = API;
}
public void setAllowedNames(String AllowedStoes){
this.AllowedNames = AllowedNames;
}
@XmlElement
public String getConsumer(){
return Consumer;
}
@XmlElement
public String getAPI(){
return API;
}
@XmlElement
public String getAllowedNames(){
return AllowedNames;
}
}
类中请求映射到的函数
@POST
@Path("/request")
@Consumes(MediaType.APPLICATION_XML)
public Response getRequest(KeyProvision keyInfo){
/* StringReader reader = new StringReader(keyInfo); // this code just leads to an execution failure for some reason
try{
JAXBContext jaxbContext = JAXBContext.newInstance(KeyProvision.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
KeyProvision api = (KeyProvision) jaxbUnmarshaller.unmarshal(reader);
System.out.println(api);
} catch(JAXBException e){
e.printStackTrace();
}
*/
String result = "Track saved : " + keyInfo;
return Response.status(201).entity(result).build() ;
// return "success" ;
}
如果我改变
public Response getRequest(KeyProvision keyInfo)
到
我可以看到请求已被接受,但未存储为POJO对象
如果我将其保留为public Response getRequest(KeyProvision keyInfo)
,则会出现一个400错误,并显示以下消息客户端发送的请求在语法上不正确。
当我尝试发出请求时,在我的REST客户端中
这是我的请求主体:
<?xml version="1.0" encoding="UTF-8"?>
<KeyProvision>
<Consumer> testConsumer </Consumer>
<API>posting</API>
<AllowedNames> google</AllowedNames>
</KeyProvision>
测试消费者
邮寄
谷歌
这里我缺少的是,通过JAXB默认命名规则阻止从XML到POJO的成功解组,它希望元素名以小写开头。您需要在
@XmlRootElement
和@XmlElement
上指定名称以匹配您的文档
@XmlRootElement(name="KeyProvision")
public class KeyProvision {
及
JAXB调试技巧
当解组无法正常工作时,请尝试填充对象模型并将其编组以查看预期的文档结构。谢谢,先生,这非常有帮助,案例就是问题所在。
@XmlRootElement(name="KeyProvision")
public class KeyProvision {
@XmlElement(name="Consumer")
public String getConsumer(){