tags:

views:

330

answers:

2

How do I tell Xstream to serialize only fields which are annotated explicitly and ignore the rest?

I am trying to serialize a hibernate persistent object and all proxy related fields get serialized which I don’t want in my xml.
e.g.

<createdBy class="com..domain.Users " reference="../../values/createdBy"/>

is not something I want in my xml.

Edit: I don’t think I made this question clear. A class may inherit from a base class on which I have no control (as in hibernate’s case) on the base class properties.

public class A {
    private String ShouldNotBeSerialized;
}

public class B extends A {
    @XStreamAlias("1")
    private String ThisShouldbeSerialized;
}

In this case when I serialize class B, the base class field ShouldNotBeSerialized will also get serialized. This is not something I want. In most circumstances I will not have control on class A.

Therefore I want to omit all fields by default and serialize only fields for which I explicitly specify the annotation. I want to avoid what GaryF is doing, where I need to explicitly specify the fields I need to omit.

+1  A: 

You can omit fields with the @XstreamOmitField annotation. Straight from the manual:

@XStreamAlias("message")
class RendezvousMessage {

    @XStreamOmitField
    private int messageType;

    @XStreamImplicit(itemFieldName="part")
    private List<String> content;

    @XStreamConverter(SingleValueCalendarConverter.class)
    private Calendar created = new GregorianCalendar();

    public RendezvousMessage(int messageType, String... content) {
        this.messageType = messageType;
        this.content = Arrays.asList(content);
    }
}
GaryF
A: 

I guess the only direct way is to dive into writting a MapperWrapper and exclude all fields you have not annotated. Sounds like a feature request for XStream.

Christopher Oezbek