2014-01-30 67 views
1

我有以下的類,它代表一個POJO對象JAXB拆封不成功使用的球衣

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

回答

2

通過JAXB默認的命名規則,將預期的元素名稱下手小寫。您需要在@XmlRootElement@XmlElement上指定名稱以匹配您的文檔。

@XmlRootElement(name="KeyProvision") 
public class KeyProvision { 

而且

@XmlElement(name="Consumer") 
public String getConsumer(){ 

JAXB的調試技巧

當解組工作不正常嘗試填充對象模型和編組出來看到預期的文件結構。

+1

謝謝先生,這是非常有幫助的,案件是問題所在。 – user1801279