【问题标题】:Serialize BiMap with xStream使用 xStream 序列化 BiMap
【发布时间】:2014-10-25 21:11:31
【问题描述】:

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

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 为空,我会在解组数据时收到以下异常:

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)
...

使用Converter后生成的Output(BiMap为空时!)如下:

<ObjectToSerialize>
  <serializeMap class="com.google.common.collect.HashBiMap"/>
</ObjectToSerialize>

谁能告诉我,我做错了什么?

【问题讨论】:

    标签: java xml guava xstream bimap


    【解决方案1】:

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

    public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
        final HashMap<?, ?> serializedMap = (HashMap<?, ?>) context.convertAnother(null, HashMap.class);
        return convertMapToBiMap(serializedMap);
    }
    

    这适用于空地图。

    【讨论】:

    • 像魅力一样工作,谢谢!我想我必须在 API 中进一步挖掘才能理解,为什么这是有效的。
    • 谢谢 我很好奇你是怎么想出来的?该函数没有 javadoc!
    • getValue() 将解析器推进到元素的结束标记。之后,无法读取任何属性,因此出现错误。非常晦涩。
    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 2013-02-08
    • 1970-01-01
    • 2015-04-13
    • 2013-03-24
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多