简体   繁体   中英

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

Say I'd like 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, eg 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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM