Scala Pickling用于Json序列化和反序列化?

3

对于我的项目dijon,我想知道是否可以使用Scala pickling进行JSON 序列化反序列化。具体来说,我希望实现以下两个辅助方法:def toJsonString(json: JSON, prettyPrint: Boolean = false): Stringdef fromJsonString(json: String): JSON。如何使用pickling创建这两个方法?


这可能是你的答案。 - David Weber
你可以使用 fromJsonString[A] 和编译时宏,或者使用运行时反射的 fromJsonString 无类型方法。请参考 @DavidWeber 的建议。不确定 Pickling 是否已经支持 Scala 2.11。 - DCKing
FYI,maven central上有Scala 2.11版本的scala-pickling。 - David Weber
2个回答

7

这取决于对你最为方便的使用方式。以下是你可以选择的大致方案:

 import scala.pickling._, json._    

 // Uses macros implicitly on Scope
 def toJSONString[A](obj: A, prettyPrint: Boolean = false)(implicit pickler: A => JSONPickle) = {
    val json = pickler(obj)
    myPrettyPrinter.print(json.value, prettyPrint)
 }

 // Uses macros defined elsewhere
 def toJSONString(obj: Any, prettyPrint: Boolean = false) = {
    val json = classToPicklerMap(obj.getClass)(obj)
    myPrettyPrinter.print(json.value, prettyPrint)
 }

 // Uses runtime reflection
 def toJSONString(obj: Any, prettyPrint: Boolean = false) = {
    val json = obj.pickle
    myPrettyPrinter.print(json.value, prettyPrint)
 }

 // Uses macros implicitly on scope
 def fromJSONString[A](json: String)(implicit unpickler: JSONPickle => A): A = {
    unpickler(JSONPickle(json))
 }

 // Uses macros defined elsewhere #1
 def fromJSONString[A](json: String)(implicit c: ClassTag[A]) = {
    classnameToUnpicklerMap(c.runtimeClass.getName)(json).asInstanceOf[A]
 }

 // Uses macros defined elsewhere #2
 def fromJSONString(json: String): Any = {
    val className = parseClassName(json) // Class name is stored in "tpe" field in the JSON    
    classnameToUnpicklerMap(className)(json)
 }

 // Uses runtime reflection
 def fromJSONString(json: String) = JSONPickler(json).unpickle

0

我没有使用过Scala Pickling,但是它在Github上说它还处于早期开发阶段。你也可以尝试一下Spray JSON。它同样支持你需要的功能。


我知道这是早期阶段。我不是在寻找一个标准的JSON序列化器 - 如果我想要的话,有很多选择(如argonaut、json-4s、rapture.io)。我特别关注pickling的使用方式,因为它似乎是未来的趋势,并由Scala核心团队开发,具有一些有趣的概念(编译时宏用于序列化)。 - pathikrit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接