0

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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
nrvaller
  • 353
  • 6
  • 18
  • BEWARE: Json4s is [vulnerable under DoS/DoW attacks](https://github.com/json4s/json4s/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+denial)! – Andriy Plokhotnyuk Aug 22 '20 at 07:48

1 Answers1

0

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.

Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25