如何让XStream很好地输出Scala列表?我可以写自定义转换器吗?

时间:2009-11-18 03:54:04

标签: generics list scala xstream

此代码:

println(new XStream.toXML(List(1,2,3)))

生成这个XML:

<scala.coloncolon serialization="custom">
  <unserializable-parents/>
  <scala.coloncolon>
    <int>1</int>
    <int>2</int>
    <int>3</int>
    <scala.ListSerializeEnd/>
  </scala.coloncolon>
</scala.coloncolon>

相反,我喜欢这个:

<list>
  <int>1</int>
  <int>2</int>
  <int>3</int>
</list>

这与通用java集合的序列化方式类似。这是最好的方法吗?

通过实现我自己的转换器,我已经完成了大部分工作,但我仍然坚持使用unmarshal方法,它不清楚如何实例化一个空列表......

class ListConverter( _mapper : Mapper )  extends AbstractCollectionConverter(_mapper) {
  /** Helper method to use x.getClass
   * 
   * See: http://scalide.blogspot.com/2009/06/getanyclass-tip.html
   */
  def getAnyClass(x: Any) = x.asInstanceOf[AnyRef].getClass

  def canConvert( clazz: Class[_]) = {       
    classOf[::[_]] == clazz
  }

  def marshal( value: Any, writer: HierarchicalStreamWriter, context: MarshallingContext) = {
    val list = value.asInstanceOf[List[_]]
    for ( item <- list ) {      
      writeItem(item, context, writer)
    }
  }

  def unmarshal( reader: HierarchicalStreamReader, context: UnmarshallingContext ) = {
    println(context.getRequiredType())
    var list : List[_] = createCollection(context.getRequiredType()).asInstanceOf[List[_]]
    while (reader.hasMoreChildren()) {
      reader.moveDown();
      val item = readItem(reader, context, list);
      list = item :: list
      reader.moveUp();
    }
    list
  }
}

object ListConverter {
  def configureXStream( stream: XStream ) = {
    stream.alias("list", classOf[::[_]])
    stream.registerConverter( new ListConverter(stream.getMapper) )        
  }
}

2 个答案:

答案 0 :(得分:2)

发布问题后几秒钟,答案就出现了,这是unmarshal的一个有效实现:

  def unmarshal( reader: HierarchicalStreamReader, context: UnmarshallingContext ) = {
    var list : List[_] = Nil 
    while (reader.hasMoreChildren()) {
      reader.moveDown();
      val item = readItem(reader, context, list);
      list = list ::: List(item) // be sure to build the list in the same order
      reader.moveUp();
    }
    list
  }

答案 1 :(得分:1)

只有一个空列表实例,即对象Nil