Java XStream - How to ignore some elements

Since XStream 1.4.5 durring marshaller declaration it's enough to use ignoreEnknownElements() method:

XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.getXStream().ignoreUnknownElements();
...

to ignore unnecessary elements.


Unfortunately overriding Mapper behaviour mentioned here does not work with implicit collections or annotations. I checked with version 1.4.3. So the obvious solution I found was to mock ignored fields with ommiting annotation. Works perfect for me but a bit boring to create them every time.

@XStreamOmitField
private Object ignoredElement;

Simply define below anonymous class after Xtream deceleration.

XStream xstream = new XStream(new DomDriver()){  
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                        try {
                            return definedIn != Object.class || realClass(fieldName) != null;
                        } catch(CannotResolveClassException cnrce) {
                            return false;
                        }
                    }
                };
            }
        };

Tags:

Java

Xstream