Home > other >  Map different value to the case class property during serialization and deserialization using Jackso
Map different value to the case class property during serialization and deserialization using Jackso

Time:09-17

I am trying to deserialize this JSON using Jackson library -

{
    "name": "abc",
    "ageInInt": 30
}

To the case class Person

case class Person(name: String, @JsonProperty(value = "ageInInt")@JsonAlias(Array("ageInInt")) age: Int)

but I am getting -

No usable value for age
Did not find value which can be converted into int
org.json4s.package$MappingException: No usable value for age
Did not find value which can be converted into int

Basically, I want to deserialize the json with the different key fields ageInInt to age.

here is the complete code -

val json =
        """{
          |"name": "Tausif",
          |"ageInInt": 30
          |}""".stripMargin



      implicit val format = DefaultFormats
      println(Serialization.read[Person](json))

CodePudding user response:

You need to register DefaultScalaModule to your JsonMapper.

import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.core.`type`.TypeReference
import com.fasterxml.jackson.annotation.JsonProperty

val mapper = JsonMapper.builder()
  .addModule(DefaultScalaModule)
  .build()

case class Person(name: String, @JsonProperty(value = "ageInInt") age: Int)

val json =
        """{
          |"name": "Tausif",
          |"ageInInt": 30
          |}""".stripMargin

  val person: Person = mapper.readValue(json, new TypeReference[Person]{})

println(person) // Prints Person(Tausif,30)
  • Related