使用Jerkson将JSON反序列化为用户定义的案例类

前端之家收集整理的这篇文章主要介绍了使用Jerkson将JSON反序列化为用户定义的案例类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用Jerkson处理 Scala中的 JSON时遇到了这个优秀的 tutorial.特别是,我有兴趣将JSON反序列化为用户定义的case类.这篇文章有一个简单的例子
  1. case class Simple(val foo: String,val bar: List[String],val baz: Map[String,Int])
  2.  
  3. object SimpleExample {
  4. def main(args: Array[String]) {
  5. import com.codahale.jerkson.Json._
  6. val simpleJson = """{"foo":42,"bar":["a","b","c"],"baz":{"x":1,"y":2}}"""
  7. val simpleObject = parse[Simple](simpleJson)
  8. println(simpleObject)
  9. }
  10. }

运行它时出现此错误,我在Play 2.0.1,Scala 2.9.1-1,Jerkson 0.5.0.

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

在Google网上论坛中也找到了this,但没有帮助.

有任何想法吗?

解决方法

不幸的是我不知道Jerkson,但Spray-Json让这类东西变得简单.以下示例来自 Spray-Json readme
  1. case class Color(name: String,red: Int,green: Int,blue: Int)
  2.  
  3. object MyJsonProtocol extends DefaultJsonProtocol {
  4. implicit val colorFormat = jsonFormat4(Color)
  5. }
  6.  
  7. import MyJsonProtocol._
  8.  
  9. val json = Color("CadetBlue",95,158,160).toJson
  10. val color = json.convertTo[Color]

这是与someone’s git repository略有不同的例子:

  1. package cc.spray.json.example
  2.  
  3. import cc.spray.json._
  4.  
  5.  
  6. object EnumSex extends Enumeration {
  7. type Sex = Value
  8. val MALE = Value("MALE")
  9. val FEMALE = Value("FEMALE")
  10. }
  11.  
  12. case class Address(no: String,street: String,city: String)
  13.  
  14. case class Person(name: String,age: Int,sex: EnumSex.Sex,address: Address)
  15.  
  16. object SprayJsonExamples {
  17. def main(args: Array[String]) {
  18. val json = """{ "no": "A1","street" : "Main Street","city" : "Colombo" }"""
  19. val address = JsonParser(json).fromJson[Address]
  20. println(address)
  21.  
  22. val json2 = """{ "name" : "John","age" : 26,"sex" : 0,"address" : { "no": "A1","city" : "Colombo" }}"""
  23.  
  24. val person = JsonParser(json2).fromJson[Person]
  25. println(person)
  26. }
  27. }

猜你在找的JavaScript相关文章