6

这段代码:

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 集合的序列化方式。最好的方法是什么?

通过实现我自己的转换器,我已经完成了大部分工作,但我被困在解组方法上,不清楚如何实例化一个空列表......

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) )        
  }
}
4

2 回答 2

2

发布问题后不到几秒钟,答案就来了,这是解组的工作实现:

  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
  }
于 2009-11-18T04:02:31.910 回答
1

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

于 2009-11-18T10:33:02.967 回答