Search code examples
scalashapelessargonautargonaut-shapeless

JSON of object of type Any and a TypeTag


Given an object of type Any and its TypeTag, how can Argonaut/Shapeless be used to create JSON of it?

  case class Person(name: String, age: Int)

  // somewhere in the code where type of 'any' is known,
  // and we preferrably dont want to include information
  // about JSON capabilities (i.e. prefer not to include
  // implicit EncodeJson[Person])
  val tt = typeTag[Person].asInstanceOf[TypeTag[Any]]
  val any = Person("myname", 123).asInstanceOf[Any]

  //somewhere else in the code where type of 'any' is unknown, but we got the TypeTag 'tt'
  implicit val e: EncodeJson[ ??? ] = ??? //somehow utilize 'tt' here?
  println(any.asJson)

Solution

  • I don't think this is possible without using reflection, i.e. with compile-time type safety. As soon as you cast the type tag to TypeTag[Any], the compiler can't use it anymore to resolve the implicit EncodeJson value. As far as I know it is impossible to resolve implicit parameters at runtime. There is toolbox.inferImplicitValue, but I don't think this helps either.

    If you know all possible types, you could maybe use a match/case statement to select the EncodeJson val for your object based on the runtime type, and pass it explicitly.

    I would recommend to preserve the EncodeJson information for the object, though.