Xstream - reuse default converter in user converter

I use xstream to process the xml string, but some fields of the object have changed between versions, so I implement a custom converter. The following is a summary of field changes, and only the first two types of fields 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 process each of the fields specifically, which leads to a lot of "else if" conditions in the unmarshal () method

 package abcreports; 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 that do not change for the standard xstream converter?

+6
source share
1 answer

The question is a bit outdated, but nonetheless, it took me a while to collect the bit.

A simple solution is to extend the ReflectionConverter instead of implementing raw Converter . ReflectionConverter is the default converter in XStream, so redefine the necessary and super everything else. Then new XStream().register your new converter, and you are good.

+3
source

Source: https://habr.com/ru/post/888885/


All Articles