Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON into user-defined case classes with Jerkson

I came across this excellent tutorial on processing JSON in Scala using Jerkson. In particular, I am interested in deserializing JSON into user-defined case classes. The article has a simple example

case class Simple(val foo: String, val bar: List[String], val baz: Map[String,Int])

object SimpleExample {
  def main(args: Array[String]) {
    import com.codahale.jerkson.Json._
    val simpleJson = """{"foo":42, "bar":["a","b","c"], "baz":{"x":1,"y":2}}"""
    val simpleObject = parse[Simple](simpleJson)
    println(simpleObject)
  }
}

I got this error running it, I am on Play 2.0.1, Scala 2.9.1-1, Jerkson 0.5.0.

Execution exception [[ParsingException: Unable to find a case accessor

Also found this on Google Groups but it isn't helpful.

Any ideas?

like image 264
Bob Avatar asked Nov 13 '12 17:11

Bob


1 Answers

Unfortunately I don't know Jerkson, but Spray-Json makes this type of stuff easy. The example below is from the Spray-Json readme:

 case class Color(name: String, red: Int, green: Int, blue: Int)

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val colorFormat = jsonFormat4(Color)
}

import MyJsonProtocol._

val json = Color("CadetBlue", 95, 158, 160).toJson
val color = json.convertTo[Color]

Here's a slightly different example from someone's git repository:

package cc.spray.json.example

import cc.spray.json._


object EnumSex extends Enumeration {
  type Sex = Value
  val MALE = Value("MALE")
  val FEMALE = Value("FEMALE")
}

case class Address(no: String, street: String, city: String)

case class Person(name: String, age: Int, sex: EnumSex.Sex, address: Address)

object SprayJsonExamples {
  def main(args: Array[String]) {
    val json = """{ "no": "A1", "street" : "Main Street", "city" : "Colombo" }"""
    val address = JsonParser(json).fromJson[Address]
    println(address)

    val json2 = """{ "name" : "John", "age" : 26, "sex" : 0 , "address" : { "no": "A1", "street" : "Main Street", "city" : "Colombo" }}"""

    val person = JsonParser(json2).fromJson[Person]
    println(person)
  }
}
like image 124
Jack Avatar answered Nov 04 '22 04:11

Jack