【问题标题】:How to drop null field while unmarshalling the xml to java object with jaxb如何在使用 jaxb 将 xml 解组为 java 对象时删除空字段
【发布时间】:2018-05-20 22:35:14
【问题描述】:

我想在使用 jaxb 解组响应(xml 响应)时删除空字段

例如在解组下面的 xml 响应 usimg jaxb 时

客户 [name=null, age=20, id=100]

是否有任何使用 jaxb 省略空字段的方法,我期望在响应下方

客户 [年龄=20,id=100]

还有其他方法可以实现吗?

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}


XML RESPONSE


        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <customer id="100">
        <age>29</age>
    </customer>

【问题讨论】:

    标签: java


    【解决方案1】:

    我试图重现发生的事情:

        Customer c = new Customer();
        c.setAge(20);
        c.setName(null);
        c.setId(100);
    
        JAXBContext context = JAXBContext.newInstance(Customer.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(c, sw);
    
        String xmlString = sw.toString();
        System.out.print(xmlString);
    

    返回:

     <?xml version="1.0" encoding="UTF-8" standalone="yes"?><customer id="100"><age>20</age></customer>
    

    这看起来像你渴望收到的东西。 您能否提供在打印空字段时如何处理 XML?

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多