xstream - reusing the default converter in a custom converter
Asked Answered
L

1

9

I'm using xstream to process an xml string but some fields of the object have changed between versions, so i'm implementing a custom converter. A summary of the field changes is listed below, and only the first two field types are different.

Field    type1      type2
a        short      String
b        String     Object
c        List       List
d        Object     Object
.
.
.
x        String     String

My current converter is implemented to handle each of the fields specifically, which leads to a large number of 'else if' conditions within the unmarshal() method

package a.b.c.reports;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class MyConverter implements Converter {

..

@Override
public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {

    while (reader.hasMoreChildren()) {
        reader.moveDown();
        if(reader.getNodeName().equals("a"))
        {
            a = reader.getValue();
        }
        else if (reader.getNodeName().equals("b")) 
        {
            b = (Object) context.convertAnother(reader, Object.class);
        } 
        else if(reader.getNodeName().equals("c"))
        {
            a = reader.getValue();
        }
        ..
        ..
    }
}

Is there a smarter way to delegate the processing of fields who's types have not changed to the default xstream converter?

Lithe answered 24/5, 2011 at 8:54 Comment(0)
N
5

The question is a bit stale, but nevertheless took me some time to gather the bits.

Simple solution to that is to extend the ReflectionConverter instead of implementing the raw Converter interface. ReflectionConverter is the default converter in the XStream so override what's needed and super everything else. Then new XStream().register your new converter and you're good.

Nev answered 16/10, 2015 at 7:50 Comment(1)
It can be registered inline like this: xStream.registerConverter(new ReflectionConverter(xStream.getMapper(), xStream.getReflectionProvider()) { ... }); where xs is the XStream at hand.Boo

© 2022 - 2024 — McMap. All rights reserved.