Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore JAXB annotated properties in a parent class?

We have a class with a JAXB annotation on one property. We then have several subclasses which annotate the rest of the important data. We have one subclass, however, where we want to ignore the parent class annotation so that it does not get marshalled. Here's some example code.

Parent class:

@XmlType(name="Request")
@XmlAccessorType(XmlAccessorType.NONE)
public abstract class Request {
    @XmlElement(required=true)
    private UUID uuid;

    ... setter/getter
}

Now for the subclass:

@Xsd(name="concreteRequest")
@XmlRootElement("ConcreteRequest")
@XmlType(name="ConcreteRequest")
@XmlAccessorType(XmlAccessorType.FIELD)
public class ConcreteClass {
    @XmlElement(required=true)
    private String data1;
    @XmlElement(required=true)
    private String data1;

    ... setters/getters ...
}

When I masrhall an instance of ConcreteClass I get the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ConcreteRequest>
    <uuid>uuid</uuid>
    <data1>data</data1>
    <data2>data</data3>
</ConcreteRequest>

Where I want XML like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ConcreteRequest>
    <data1>data</data1>
    <data2>data</data3>
</ConcreteRequest>

We have other implementations of Request, however that do require the UUID, this is just a special case. Is there a way to ignore the UUID field in my ConcreteRequest?

like image 809
prozaak Avatar asked Oct 01 '12 11:10

prozaak


1 Answers

I hope, I understood your problem. Here is the solution.

JAXB provides @XmlTransient(javax.xml.bind.annotation.XmlTransient)(javadoc) to ignore any field during marshalling.

Override the field "uuid" as @XmlTransient in your derived class (ConcreteRequest.class) along with its correspoding Getter/Setter method. It is necessary to override the Getter/Setter methods also, these will be invoked during marshalling.

@Xsd(name="concreteRequest")
@XmlRootElement("ConcreteRequest")
@XmlType(name="ConcreteRequest")
@XmlAccessorType(XmlAccessorType.FIELD)
public class ConcreteClass {
    @XmlElement(required=true)
    private String data1;
    @XmlElement(required=true)
    private String data2;
    @XmlTransient
    private UUID uuid;

    ... setters/getters ...
}

This will override your Base Class attribute.

Get back to me for more information.

like image 157
omega Avatar answered Oct 20 '22 00:10

omega