简体   繁体   中英

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.

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.

I read source code for ArrayConverter and AbstractCollectionConverter and rewrote unmarshal as follow:

while(reader.hasMoreChildren()) {    
    reader.moveDown(); 
    Class type = HierarchicalStreams.readClassType(reader, mapper); 
    Object item = context.convertAnother(context.currentObject(), type);  
    itemList.add((Item)item); 
    reader.moveUp(); 
}

But I got an error in case of cyclic references. So the best way was sudgested by Ryan Stewart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM