Search code examples
javaconvertersxstream

custom converter with xstream


I need a custom convertor for my class Scope:

class Scope {
    private final String name;
    private final SomeProp prop;
    private final Item[] items;
    //...
}

I registered my converter for SomeProp. But I want to use default converter for Item (and all sub-classes).

How I can do it?

I tried to override marshal/unmarshal:

public void marshal(Object val, HierarchicalStreamWriter writer, 
          MarshallingContext context) {
    //... saving name and prop
    writer.startNode("items");

    ArrayConverter conv = new ArrayConverter(mapper);
    assert(conv.canConvert(items.members.getClass()));
    conv.marshal(items.members, writer, context);

    writer.endNode);
}

public Object unmarshal(HierarchicalStreamReader reader,
    UnmarshallingContext context) {
    //... reading name and prop
    reader.moveDown();

    assert("items".equals(reader.getNodeName()));

    ArrayConverter conv = new ArrayConverter(mapper);
    Item[] items = (Item[])conv.unmarshal(reader, context);
    //...
}

but by some reason unmarshal is not working.


Solution

  • Your description isn't very clear, but I think you're trying to do far more work than is needed. If you want a custom converter for SomeProp and default for everything else, all you have to do is

    Scope scope = ...;
    XStream xstream = new XStream();
    xstream.registerConverter(new SomePropConverter());
    String xml = xstream.toXML(scope);
    

    If I missed something in your question, please clarify.