Search code examples
scalajacksonjackson-module-scala

Using Scala Jackson for JSON deserialization?


I am new to scala and trying to map my json to an object. I have found jackson-scala-module but unable to figure out how to use it. A small example might be of help.

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

I want to map this to Person(name: String, age: Int, height: Int, weight: Int)

Till now I have been trying using this:

import com.fasterxml.jackson.databind.ObjectMapper

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

Dependency I am using:

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

Am I missing on anything?

EDIT:

[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?)

Solution

  • In order to make it work, you need to register DefaultScalaModule with the object mapper:

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

    Also, you need to update your case class and provide Jackson with property name to field name binding:

    case class Person(@JsonProperty("DP-Name") name: String, 
                      @JsonProperty("DP-Age") age: Int, 
                      @JsonProperty("DP-height") height: Int, 
                      @JsonProperty("DP-weight") weight: Int)