简体   繁体   中英

How to drop null field while unmarshalling the xml to java object with jaxb

I want to drop null field while unmarshalling response (xml response) using jaxb

for example while unmarshalling the below xml response usimg jaxb

Customer [name=null, age=20, id=100]

is there any to omit null field using jaxb i am expecting below response

Customer [ age=20, id=100]

is there any way other i can achieve this?

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>

I tried to reproduce what happens:

    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);

Returns:

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

which looks like what you aspire to receive. Could you please provide how you process the XML when the null field is printed?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM