开发者

How can I serialize (and later deserialize) a generic type in Scala?

开发者 https://www.devze.com 2022-12-11 14:05 出处:网络
Say I\'d li开发者_开发技巧ke to implement something like this: def serialize( list: List[_] ) : Node = {

Say I'd li开发者_开发技巧ke to implement something like this:

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

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

How do I get the type of the List, e.g. T in List[T] so I can write that out? Or do I need it? How can I instantiate the list in deserialize?


Is this close to what you're looking for? Note that it only will serialize homogenous lists.

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>
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号