How does XStream choose its converters?

The only documentation on XStream converters I can find is in these two pages:

When XStream parses XML input, it uses ConverterLookup

(and by default a DefaultConverterLookup

) to find out which converter to use by class. I'd like to configure my XStream

mapper to use my own ConverterLookup

, but I only see the method getConverterLookup()

, not the corresponding compositor.

I have an instance where an XStream meets a value Date

in XML and returns using the appropriate one DateConverter

. I want it to use a different converter, which (I believe) means I need to install / register my own Converter

impl. I just can't figure out how to do it. Thanks in advance.

+3


source to share


1 answer


First of all, your question actually consists of two unrelated questions, I will try to answer both of them.

Converters

To your second question about date conversion. Which, in my opinion, is the reason why you are here.

The basic way to add your own converter is pretty simple, the method registerConverter

should give you a clue. If you're wondering how to implement it Converter

, I suggest you take a look at one of the many converters already provided by XStream. In addition, I feel like I should mention the priority of the converters.

Converters can be registered with explicit priority. By default, they are registered in XStream.PRIORITY_NORMAL. Inverters of the same priority will be used in the reverse order in which they were registered. The default converter, that is, the converter to be used if another registered converter is not suitable, can be registered with the priority XStream.PRIORITY_VERY_LOW. XStream uses ReflectionConverter as a fallback converter by default.

In other terms, given that two converters accepting the same classes, the last added one will be used.

ConverterLookup



To answer how you can use yours ConverterLookup

, there are two ways that can give the same results, personally I would go for alternative 2.

1) OverridinggetConverterLookup

    XStream xs = new XStream(){
        @Override
        public ConverterLookup getConverterLookup() {
            return new ConverterLookup() {

                public Converter lookupConverterForType(Class type) {
                    //Do your magic here
                }
            };
        }
    };

      

2) UsingMapper

In this case, I would save DefaultMapper

and use it MapperWrapper

for my new mappings instead . (Look buildMapper

inside XStream.java

to see some of the defaults) Initialize like this:

    ClassLoader classLoader = new ClassLoaderReference(new CompositeClassLoader());
    Mapper mapper = new DefaultMapper(classLoader);
    mapper = new MyOwnMapperWrapper(mapper);
    XStream xs = new XStream(null, mapper, new XppDriver());

      

+4


source







All Articles