加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:49:44 所属栏目:安全 来源:网络整理
导读:这段代码: println(new XStream.toXML(List(1,2,3))) 生成这个XML: scala.coloncolon serialization="custom" unserializable-parents/ scala.coloncolon int1/int int2/int int3/int scala.ListSerializeEnd/ /scala.coloncolon/scala.coloncolon 相反,我
这段代码:

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,list);
      list = item :: list
      reader.moveUp();
    }
    list
  }
}

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

解决方法

发布问题后不到几秒钟,答案就出现在我面前,这是一个解组的工作实现:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读