For my project, dijon, I was wondering if it is possible to use Scala pickling for JSON serialization and deserialization.
Specifically, I want something like this def toJsonString(json: JSON, prettyPrint: Boolean = false): String
and def fromJsonString(json: String): JSON
. How can I use pickling to create these two helper methods?
Asked
Active
Viewed 1,606 times
3

pathikrit
- 32,469
- 37
- 142
- 221
-
[This](http://stackoverflow.com/questions/18725699/scala-pickling-and-type-parameters) may be your answer. – David Weber May 19 '14 at 09:11
-
You get either `fromJsonString[A]` and compile time macros, or `fromJsonString` untyped with runtime reflection. See @DavidWeber's suggestion. Not sure Pickling works with Scala 2.11 yet. – DCKing May 20 '14 at 13:26
-
FYI, there is a Scala 2.11 version of scala-pickling on maven central. – David Weber May 22 '14 at 11:02
2 Answers
7
It really depends on what is most convenient for your use. These are rough sketches of the choices you have:
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

DCKing
- 4,253
- 2
- 28
- 43
0
I haven't used Scala Pickling, but it says on its Github repo that it's in its early dev stages. You may also want to try out Spray JSON. It supports the things you need as well.

Haris Osmanagić
- 1,249
- 12
- 28
-
I am aware that it is early stage. I am not looking for a canonical JSON serializer - there is plenty out there (argonaut, json-4s, rapture.io) to use if I wanted to. I am specifically interested in how pickling can be used since it seems to be the future and is developed by the core Scala group itself and has some interesting concepts (compile time macros for serialization). – pathikrit May 14 '14 at 16:41