jsonscalajson4s

deserializing json4s with generic type


Update: Looked closer into the rest of my code and I had an issue elsewhere which is why it was not working. Thanks

I wanted to know if one can use json4 serializer to deserialize and object that uses generic.

My json data has similar traits with different information for one part

For example, I have Superhero and who has skills different

*Json Data

{
  "type": "Blue",
  "name": "Aquaman",
  "age": "4",
  "skills": {
    "Cooking": 9,
    "Swimming": 4
  }
}
{
  "type": "Red",
  "name": "Flash",
  "age": "8",
  "skills": {
    "Speed": 9,
    "Punctual": 10
  }
}

So what I wanted to do was

case class Superhero[T](
  `type`: String,
  name: String,
  age: Int,
  skills: T
)

and the respective skill case class

case class BlueSkill(
  Cooking: Int,
  Swimming: Int
)
case class RedSkill(
  Speed: Int,
  Punctual: Int
)

but when I read and try to map it to another object I get null in my dataframe.

val bluePerson = read[Superhero[BlueSkill]](jsonBody)

So wanted to know if reading generic object is possible with json4.


Solution

  • Sure it can be done, why would it work any differently from non-generic types?

    import org.json4s.native.{Serialization => S}
    import org.json4s.DefaultFormats
    implicit val fmts = DefaultFormats
      S.read[Superhero[RedSkill]]("""|{
                                     |  "type": "Red",
                                     |  "name": "Flash",
                                     |  "age": 8,
                                     |  "skills": {
                                     |    "Speed": 9,
                                     |    "Punctual": 10
                                     |  }
                                     |}""".stripMargin)
    
    
    

    But frankly, I'd stay away from json4s or any other introspection nonsense and use a typeclass-based library such as circe instead.