我使用Jerkson在Scala中处理JSON时遇到了这个优秀的tutorial。特别是,我有兴趣将JSON反序列化为用户定义的case类。这篇文章有一个简单的例子
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)
}
}
运行它时出现此错误,我在Play 2.0.1,Scala 2.9.1-1,Jerkson 0.5.0。
Execution exception [[ParsingException: Unable to find a case accessor
在Google网上论坛中也找到this,但没有帮助。
有什么想法吗?
答案 0 :(得分:6)
不幸的是我不知道Jerkson,但Spray-Json让这类东西变得简单。以下示例来自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]
略有不同的示例
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)
}
}