使用 Scala Jackson 进行 JSON 反序列化?

Using Scala Jackson for JSON deserialization?

我是 scala 的新手,正在尝试将我的 json 映射到一个对象。我找到了 jackson-scala-module 但无法弄清楚如何使用它。一个小例子可能会有帮助。

val json = { "_id" : "jzcyluvhqilqrocq" , "DP-Name" : "Sumit Agarwal" , "DP-Age" : "15" , "DP-height" : "115" , "DP-weight" : "68"}

我想将其映射到 Person(name: String, age: Int, height: Int, weight: Int)

直到现在我一直在尝试使用这个:

import com.fasterxml.jackson.databind.ObjectMapper

Val mapper = = new ObjectMapper();    
val data = mapper.readValue(json, classOf[Person])

我正在使用的依赖项:

"com.fasterxml.jackson.module" % "jackson-module-scala_2.11" % "2.8.4"

我是不是漏了什么?

编辑:

[error] (run-main-4) com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of models.Person: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)

为了使其工作,您需要使用对象映射器注册 DefaultScalaModule:

val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)

此外,您需要更新案例 class 并为 Jackson 提供 属性 名称到字段名称绑定:

case class Person(@JsonProperty("DP-Name") name: String, 
                  @JsonProperty("DP-Age") age: Int, 
                  @JsonProperty("DP-height") height: Int, 
                  @JsonProperty("DP-weight") weight: Int)
  • 问题是您还没有注册 DefaultScalaModule ObjectMapper
lazy val mapper = new ObjectMapper() with ScalaObjectMapper
 mapper.registerModule(DefaultScalaModule)
  • 请找到我使用泛型提供的有效且详细的答案 here