【问题标题】:Scala Pickling for Json serialization and deserialization?用于 Json 序列化和反序列化的 Scala Pickling?
【发布时间】:2014-07-02 01:21:27
【问题描述】:

对于我的项目dijon,我想知道是否可以将Scala pickling 用于JSON serializationdeserialization。 具体来说,我想要像def toJsonString(json: JSON, prettyPrint: Boolean = false): Stringdef fromJsonString(json: String): JSON 这样的东西。如何使用酸洗来创建这两个辅助方法?

【问题讨论】:

  • This 可能是你的答案。
  • 你要么得到fromJsonString[A] 和编译时宏,要么得到fromJsonString 无类型的运行时反射。请参阅@DavidWeber 的建议。不确定 Pickling 是否适用于 Scala 2.11。
  • 仅供参考,maven central 上有一个 Scala 2.11 版本的 scala-pickling。

标签: json scala jsonserializer scala-pickling scala-2.11


【解决方案1】:

这真的取决于你使用什么最方便。这些是您的选择的粗略草图:

 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

【讨论】:

    【解决方案2】:

    我没有使用过 Scala Pickling,但它在其 Github 存储库中表示它处于早期开发阶段。您可能还想试试Spray JSON。它也支持你需要的东西。

    【讨论】:

    • 我知道这是早期阶段。我不是在寻找一个规范的 JSON 序列化程序——如果我愿意的话,有很多可用的(argonaut、json-4s、rapture.io)。我对如何使用酸洗特别感兴趣,因为它似乎是未来,并且是由核心 Scala 小组自己开发的,并且有一些有趣的概念(用于序列化的编译时宏)。
    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2015-02-28
    • 2020-10-23
    • 2015-03-21
    • 2012-09-05
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多