如何在Scala中序列化(以后反序列化)泛型类型?

时间:2009-11-18 03:50:37

标签: generics serialization scala

说我想实现这样的事情:

def serialize( list: List[_] ) : Node = {
  <list>
  { for ( item <- list ) yield serializeItem(item) }
  </list>
}

def deserialize( node : Node ) : List[_] = {
  // ?
}

如何获取列表的类型,例如列表中的T [T]所以我可以写出来吗?或者我需要它吗?如何在反序列化中实例化列表?

1 个答案:

答案 0 :(得分:1)

这接近你想要的吗? 请注意,它只会序列化同源列表。

package example

import scala.xml.{Node,Text}

object App extends Application {
  import Xerialize._

  val x = List(List(1,2),List(2,3,4),List(6))

  println(toXml(x))
  println(fromXml(toXml(x)))

  val z = List(Person("Joe",33),Person("Bob",44))
  println(toXml(z))
  println(fromXml(toXml(z)))
}

object Xerialize {
  def n(node: Node) = node // force to Node, better way?

  case class Person(name: String, age: Int)

  def toXml[T <% Node](t: T): Node = n(t)
  def fromXml(node: Node):Any = node match {

    case <list>{e@_*}</list> => {
      e.toList map { fromXml(_) }
    }

    case <int>{i}</int> => {
      i.text.toInt
    }

    case <person><name>{n}</name><age>{a}</age></person> => {
      Person(n.text,a.text.toInt)
    }

    case _ => {
      throw new RuntimeException("match errror")
    }
  }


  implicit def listToXml[T <% Node](l: List[T]): Node = {
    <list>{ l map { n(_) } }</list>
  }
  implicit def personToXml(p: Person): Node = {
    <person><name>{p.name}</name><age>{p.age}</age></person>
  }
  implicit def intToXml(i: Int): Node = <int>{ i.toString }</int>
}