简体   繁体   English

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

[英]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? 如何获取列表的类型,例如T in List [T],以便可以将其写出来? 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>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何反序列化具有泛型类型的对象? - How do I deserialize an object with a generic type? 如何使用消息包序列化或反序列化通用结构? - How to serialize or deserialize a generic struct with messagepack? 如何使用通用属性序列化/反序列化类? - How to serialize/deserialize a class with a generic property? 使用 Jackson,如何使用返回具有通用类型的包装器的 static 工厂方法反序列化值? - Using Jackson, how can I deserialize values using static factory methods that return wrappers with a generic type? 如何使用杰克逊反序列化泛型类型? - How to deserialize a generic type with jackson? 如何使用返回类型定义lambda函数,以后可以与泛型一起使用 - How to define a lambda function with a return type that can be used later with a generic 如何序列化一个可以作为其自身类型参数的泛型 class? - How to serialize a generic class that can be its own type parameter? 如何存储参数化方法的类型参数,然后使用它们将JSON对象转换为泛型类型的普通对象? - How can I store the type parameter(s) of a parameterized method and later use them to convert a JSON object to a plain object of the generic type? 如何在 scala 中初始化通用变量 - How can I initialize a generic variable in scala Scala-如何在使用前排除函数的泛型? - Scala - How can I exclude my function's generic type until use?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM