开发者

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 ArrayConver开发者_运维技巧ter(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜