Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)
like image 237
Sumit Agarwal Avatar asked Jun 23 '26 14:06

Sumit Agarwal


1 Answers

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)
like image 110
Mykhailo Hodovaniuk Avatar answered Jun 29 '26 00:06

Mykhailo Hodovaniuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!