Search code examples
javadictionaryxstream

How would I use XStream to produce smaller output for simple maps?


I serialize the data of my application with xstream. Since it should be read by other applications - or even viewed manuall I'd like to touch up the XML.

I have big maps of very simple types like TreeMap<Integer,Double> and TreeMap<String,Double>. I want to make my output more compact for these. Say from:

<entry>
    <int>56</int>
    <double>38.0</double>
</entry>

to <entry key="56">38.0</entry>

Unfortunately my experiments using this.aliasAttribute(Entry.class, "key", "key") fail with null pointer exception.

And I'm having problems to understand how I would write/register an Converter that would handle TreeMap<Integer,Double> but keeps the default behaviour for TreeMap<Object,MyComplexObject> .

Maybe you can point me to a solution, thanks.


maybe the stacktrace can give some information.

java.lang.NullPointerException
    at com.thoughtworks.xstream.converters.reflection.FieldDictionary.buildMap(FieldDictionary.java:128)
    at com.thoughtworks.xstream.converters.reflection.FieldDictionary.fieldOrNull(FieldDictionary.java:113)
    at com.thoughtworks.xstream.converters.reflection.FieldDictionary.field(FieldDictionary.java:92)
    at com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider.getField(PureJavaReflectionProvider.java:181)
    at com.thoughtworks.xstream.mapper.AttributeMapper.addAttributeFor(AttributeMapper.java:169)
    at com.thoughtworks.xstream.XStream.useAttributeFor(XStream.java:1226)
    at com.thoughtworks.xstream.XStream.aliasAttribute(XStream.java:1192)
    at myproject.XstreamSerializer.<init>(XstreamSerializer.java:43)

Solution

  • There is a TreeMapConverter in XStream
    May be it can help you out.
    You can further read about this here