0
votes

I have the following, and want to use jerkson in scala, but am having issues with this. I'm sure this is a very amateur error, but was hoping to get some help from here.

  scala> val orig=List("this", List("a", "b", List("c", "d")))
  orig: List[java.lang.Object] = List(this, List(a, b, List(c, d)))

 val json_ver=generate(orig)
 json_ver: String = ["this",["a","b",["c","d"]]]

 //now i want to go from json_ver back to orig list of lists
 //I've tried parse[List[Any]](json_ver)
 //parse[List[List[Any]]](json_ver)

All to no avail. I would really appreciate it if someone could point me in the right direction

1

1 Answers

2
votes

A word of warning: the original Codahale Jerkson has been abandoned and there's no official build for Scala 2.10 (although there are some Github forks for 2.10). jackson-module-scala (which jerkson wraps), on the other hand, is fully maintained and supported.

[EDIT] after clarifying the question.

The original data structure is using Lists of Any (Lists and Strings). The one that's returned from the parser is List, but lists inside of it arejava.util.ArrayList. That type is also a list, but not the same and doesn't fit in to Scala collections as natively. Among other things, it has a different implementation of toString, which is why the output is different. Note that it's still a list of Any, just not the Scala Lists.

One way to solve it would be just to use collection converters to convert to Scala:

import scala.collection.JavaConverters._
// somewhere down the line
val parsedList = parse[List[Any]](json_ver)

parsedList.foreach {
   case s: String => println("string: " + s)
   case l: util.ArrayList[Any] => doSomething(l.asScala.toList)
}

...
def doSomething(lst: List[Any]) {
   println(lst)
}

Another way is that if you were to use Jackson, you could configure it to use Java arrays:

val mapper = new ObjectMapper()
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true)
mapper.registerModule(DefaultScalaModule)
mapper.readValue[List[Any]](json_ver, classOf[List[Any]])