java - 解码时发生错误

标签 java xml jaxb marshalling unmarshalling

我不明白为什么要解码。

这是我的类(class):

@XmlRootElement(name = "privileges")
@XmlAccessorType(XmlAccessType.FIELD)
public  class Privilege {
    @XmlAttribute(name = "number_residents")
    private Integer numberResidents;
    @XmlAttribute(name = "value")
    private String value;
    @XmlElement(name = "privilege")
    private String privilage;

位于 getter、setter、equals 和 toString 之下 }

我正在尝试进行解码。

 File file = new File( "response.xml");
                JAXBContext context = JAXBContext.newInstance(Privilege.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                Privilege privilege = (Privilege) unmarshaller.unmarshal(file);
                System.out.println(privilege);

但我总是得到:

Privilege{numberResidents=null, value='null', privilage='Test privilege'}

但是在这样的文件中:

<?xml version="1.0" encoding="UTF-8"?>
<privileges>
    <privilege number_residents="3" value="bb2">Test privilege</privilege>
</privileges>

我需要你的帮助

最佳答案

您的映射不正确。

尝试:

@XmlRootElement(name = "privileges")
@XmlAccessorType(XmlAccessType.FIELD)
public class Privileges {

    @XmlElement(name="privilege")
    private Privilege privilege;

    //Getters and setters

}

@XmlAccessorType(XmlAccessType.FIELD)
public class Privilege{

    @XmlAttribute(name = "number_residents")
    private Integer numberResidents;
    @XmlAttribute(name = "value")
    private String value;
    @XmlValue
    private String privilege;

    //getters and setters

}

关于java - 解码时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619387/

相关文章:

mysql - 每个客户的 XQuery 最近订单

java - 如何解决 IllegalStateException : Failed to load ApplicationContext

java - 从 xml 响应中获取对象

java - 如何使用 JAXB 编码(marshal)/取消编码(marshal)链接的 Java 对象

java - 使用 JAXB 编码(marshal)通用对象时如何摆脱命名空间

java - 如何在 Controller 中映射两个不同的url : one url with param and the same without the param?

java - 当我们按 id 过滤列表时,如何使用 HQL 一对多查询关系

java - 当节点也有内部节点时,有没有办法映射该节点的值?

java - 在 Jax-rs Web 服务中注入(inject) HttpResponse 时出现空指针异常

java - 如何从其他maven模块获取资源文件夹(文件)?