我有以下代表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 {
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)
到
public Response getRequest(String keyInfo)
我可以看到请求已被接受但未存储为POJO对象。
如果我将其保留为public Response getRequest(KeyProvision keyInfo)
,当我尝试发出请求时,我在REST客户端中收到以下消息<u>The request sent by the client was syntactically incorrect.</u>
的400错误。
这是我的要求机构:
<?xml version="1.0" encoding="UTF-8"?>
<KeyProvision>
<Consumer> testConsumer </Consumer>
<API>posting</API>
<AllowedNames> google</AllowedNames>
</KeyProvision>
我在这里想到的是阻止从XML到POJO的成功解组
答案 0 :(得分:2)
通过JAXB默认的命名规则,它将期望元素名称以小写字母开头。您需要在@XmlRootElement
和@XmlElement
上指定名称以匹配您的文档。
@XmlRootElement(name="KeyProvision")
public class KeyProvision {
并且
@XmlElement(name="Consumer")
public String getConsumer(){
JAXB调试技巧
当unmarshal无法正常工作时,请尝试填充对象模型并将其编组以查看预期的文档结构。