【问题标题】:JAXB Unmarshaling unsuccessful using jersey使用球衣的 JAXB 解组失败
【发布时间】:2014-01-30 17:58:45
【问题描述】:

我有以下代表 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 客户端中会出现 400 错误并显示以下消息 <u>The request sent by the client was syntactically incorrect.</u>

这是我的请求正文:

<?xml version="1.0" encoding="UTF-8"?>
<KeyProvision>
<Consumer> testConsumer </Consumer>
<API>posting</API>
<AllowedNames> google</AllowedNames>
</KeyProvision>

我在这里遗漏了什么阻止了从 XML 到 POJO 的成功解组

【问题讨论】:

    标签: java xml jaxb jersey jax-rs


    【解决方案1】:

    根据 JAXB 默认命名规则,它会期望元素名称以小写字母开头。您需要在 @XmlRootElement@XmlElement 上指定名称以匹配您的文档。

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

    还有

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

    JAXB 调试技巧

    如果 unmarshal 无法正常工作,请尝试填充对象模型并将其编组以查看预期的文档结构。

    【讨论】:

    • 谢谢先生,这很有帮助,问题出在案例中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2016-01-03
    • 2012-12-27
    • 2013-08-11
    相关资源
    最近更新 更多