0

I'm trying to convert a Java object to XML using JAX-B and running into some issues. This class that I'm converting into XML has a parent class, and two fields from the class are appearing in the final XML. Applying the @XmlTransient annotation over those fields/getter methods does not seem to help. I do not want any fields in this class to be in my final XML; this parent class is used by many other classes and I don't want to mess with it. Any help is appreciated.

Sample Code:

Parent Class

public abstract class ParentClass implements Serializable{
    private transient Object modBy;
    private transient Object modOn;
    private transient boolean modded= false;
    private transient int saved= 0;

    //getters and setters

}

Child Class

public class ChildClass extends ParentClass implements Serializable {
    private String name;
    private String ID;
    private String timeStamp;

    @XmlElement
    public String getName(){
        return this.name;
    }

    @XmlElement(name="AccountID")
    public String getID{
       return this.ID;
    }
    @XmlTransient
    public String getTimestamp(){
       return this.timestamp;
    }

    //Setters
     .
     .
     .
}

Final XML Contains

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ChildClass>
    <modded>true</modded>
    <saved>0</saved>
    <name>Jason</name>
    <AccountID>185345346</AccountID>
</ChildClass>

Code to convert to to XML

JAXBContext jContext = JAXBContext.newInstance(ConcealedHandgunPermit.class);
Marshaller marshallObj = jContext.createMarshaller();
marshallObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ChildClass childClass = new ChildClass();
//set the values in object
.
.
.                   
//calling the marshall method
String path = "C:\\Users\\jasonbourne\\Desktop\\temp\\example.txt";
path = path.replace("\\", "/");
marshallObj.marshal(childClass, new FileOutputStream(path));

I do not want the fields modded and save to be on there.

wolfcubman
  • 13
  • 3
  • You have to annotate `modded` and `save` with `@XmlTransient` in parent class or ignore whole parent class by annotation `@XmlAccessorType(XmlAccessType.NONE)` look at similar question at https://stackoverflow.com/questions/3728341/ignore-a-parent-class-when-serializing-to-xml – Vadim May 14 '18 at 19:34
  • I tried that and it didn't work – wolfcubman May 14 '18 at 21:09

0 Answers0