Skip to content Skip to sidebar Skip to footer

Xstream Serialize Custom Map With Namedmapconverter

I am successfully serializing my Base class containing HashMap with NamedMapConverter. My requirements have changed and I need to change HashMap to custom Str

Solution 1:

It seems that without custom converter above is impossible to achieve. However, in this case custom converter can be provided with only slight tweaking of existing one. Problem lies in NamedMapConverter.canConvert method that has to be overridden to include custom StringDictionary class.

Following code will produce required xml output for modified Base class:

XStream xs = new XStream();
xs.alias("base", Base.class);

xs.addDefaultImplementation(StringDictionary.class, Map.class);
NamedMapConverter c = new NamedMapConverter(xs.getMapper(), "val", "key", String.class, null, String.class, true, false, xs.getConverterLookup())
{
    publicboolean canConvert(Classtype)
    {
        if (type.equals(StringDictionary.class)) returntrue;
        elsereturn super.canConvert(type);
    }
};
xs.registerConverter(c);

Another simpler (but not fully compliant) solution, is to pass StringDictionary class to NamedMapConverter constructor. However this solution will slightly change xml output.

XStream xs = newXStream();
xs.alias("base", Base.class);
NamedMapConverter c = newNamedMapConverter(StringDictionary.class, xs.getMapper(), "val", "key", String.class, null, String.class, true, false, xs.getConverterLookup());
xs.registerConverter(c);


<base><valuesclass="com.test.StringDictionary"><valkey="123">111</val><valkey="abc">aaa</val></values></base>

Post a Comment for "Xstream Serialize Custom Map With Namedmapconverter"