Search code examples
javaserializationxstream

How to ignore a type with XStream?


with XStream, how can I ignore the serialization of a defined Type (for instance, when serializing a GUI, i want to ignore all swing types)?

Or if i want to ignore all javax.* types?

Thanks in advance,
Burkhard


Solution

  • you need to write a custom converter for the types you want to ignore.

    For example, if you want to ignore the JLabels:

    public class MyJLabelConverter implements Converter {
    
        @Override
        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        }
    
        @Override
        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            return null;
        }
    
        @Override
        public boolean canConvert(Class clazz) {
            return clazz.equals(JLabel.class);
        }
    }
    

    and register it with:

    xstream.registerConverter(new MyJLabelConverter());