3

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

4

2 回答 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
于 2014-05-21T09:11:40.103 回答
0

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

于 2014-05-14T10:45:08.783 回答