首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用BiMap序列化xStream

用BiMap序列化xStream
EN

Stack Overflow用户
提问于 2014-09-01 15:43:39
回答 1查看 347关注 0票数 2

我想用xStream序列化一个xStream。由于我不喜欢xStream为BiMap自动生成的代码,所以我认为将BiMap转换为HashMap并只序列化HashMap可能是个好主意,当反序列化它时,我只是再次读取HashMap并将其转换回BiMap。因此,我提出了以下转换器策略:

代码语言:javascript
复制
public class XStreamBiMapConverterExample
{
  public void run()
  {
    XStream xStream = new XStream();
    xStream.setMode( XStream.XPATH_ABSOLUTE_REFERENCES );
    xStream.registerConverter( new BiMapConverter(), XStream.PRIORITY_VERY_HIGH );

    final String xml = xStream.toXML( new ObjectToSerialize() );

    System.out.println( xml );

    xStream.fromXML( xml );//Reading does not work, if the BiMap of ObjectToSerialize is empty
  }

  public static void main( final String[] args )
  {
    new XStreamBiMapConverterExample().run();
  }
}


class ObjectToSerialize
{
  //  Map<String, Integer> serializeMap = new HashMap<>();
  BiMap<String, Integer> serializeMap = HashBiMap.create();

  public ObjectToSerialize()
  {
    //If there is no Values, my Converter fails. With Value there is no Problem.
    //    serializeMap.put( "Hallo", 7 );
  }
}


class BiMapConverter implements Converter
{
  @Override
  public boolean canConvert( @SuppressWarnings( "rawtypes" ) final Class type )
  {
    return BiMap.class.isAssignableFrom( type );
  }

  @Override
  public void marshal( final Object source, final HierarchicalStreamWriter writer,
                       final MarshallingContext context )
  {
    final BiMap<?, ?> biMap = (BiMap<?, ?>) source;

    final HashMap<?, ?> convertBiMapToHashMap = convertMapToHashMap( biMap );

    context.convertAnother( convertBiMapToHashMap );
  }

  private <K, V> HashMap<K, V> convertMapToHashMap( final Map<K, V> map )
  {
    final HashMap<K, V> hashMap = new HashMap<>();

    for ( Entry<K, V> entry : map.entrySet() )
    {
      hashMap.put( entry.getKey(), entry.getValue() );
    }

    return hashMap;
  }

  @Override
  public Object unmarshal( final HierarchicalStreamReader reader, final UnmarshallingContext context )
  {
    final HashMap<?, ?> serializedMap =
        (HashMap<?, ?>) context.convertAnother( reader.getValue(), HashMap.class );

    return convertMapToBiMap( serializedMap );
  }

  private <K, V> BiMap<K, V> convertMapToBiMap( final Map<K, V> map )
  {
    final BiMap<K, V> biMap = HashBiMap.create();

    for ( Entry<K, V> entry : map.entrySet() )
    {
      biMap.put( entry.getKey(), entry.getValue() );
    }

    return biMap;
  }
}

这非常好,因为xStream已经可以转换HashMaps了。奇怪的是,只有当BiMap中有值时,它才能工作。如果BiMap为空,则在解组数据时得到以下异常:

代码语言:javascript
复制
Exception in thread "main" com.thoughtworks.xstream.converters.ConversionException: only START_TAG can have attributes END_TAG seen ...ize>\n  <serializeMap class="com.google.common.collect.HashBiMap"/>... @2:62 : only START_TAG can have attributes END_TAG seen ...ize>\n  <serializeMap class="com.google.common.collect.HashBiMap"/>... @2:62
---- Debugging information ----
message             : only START_TAG can have attributes END_TAG seen ...ize>\n  <serializeMap class="com.google.common.collect.HashBiMap"/>... @2:62
cause-exception     : java.lang.IndexOutOfBoundsException
cause-message       : only START_TAG can have attributes END_TAG seen ...ize>\n  <serializeMap class="com.google.common.collect.HashBiMap"/>... @2:62
class               : com.google.common.collect.HashBiMap
required-type       : com.google.common.collect.HashBiMap
converter-type      : BiMapConverter
path                : /ObjectToSerialize/serializeMap
line number         : 2
class[1]            : ObjectToSerialize
converter-type[1]   : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
version             : 1.4.6
-------------------------------
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
...

使用转换器后生成的输出(当BiMap为空时!)如下:

代码语言:javascript
复制
<ObjectToSerialize>
  <serializeMap class="com.google.common.collect.HashBiMap"/>
</ObjectToSerialize>

有人能告诉我,我做错了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-01 16:51:35

您不需要在reader.getValue()方法中调用unmarshal

代码语言:javascript
复制
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
    final HashMap<?, ?> serializedMap = (HashMap<?, ?>) context.convertAnother(null, HashMap.class);
    return convertMapToBiMap(serializedMap);
}

这将适用于一个空的Map。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25609232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档