mercredi 24 novembre 2021

Scala - How to extract Json4s with dynamic case class created with ToolBox

I defined the case class dynamically using Toolbox. And when I do extract of json4s, I get the following exception:

  import org.json4s._
  import scala.reflect.runtime._
  import scala.tools.reflect.ToolBox

  implicit val formats = DefaultFormats

  val cm = universe.runtimeMirror(getClass.getClassLoader)
  val toolBox = cm.mkToolBox()

  val parse =
    toolBox.parse(
      s"""
         | case class Person( name:String, age:String)
         | scala.reflect.classTag[ Person].runtimeClass
       """.stripMargin)

  val person = toolBox.compile( parse)().asInstanceOf[Class[_]]

  val js = JsonMethods.parse("""{ "name":"Tom","age" : "28"}""")
  val jv = js.extract[person.type ] //How do I pass the class type?

**"Exception in thread "main" org.json4s.MappingException: No constructor for type Class, JObject(List((name,JString(Tom)), (age,JString(28))))"** 

But after creating a dummy instance of the dynamically created class, Then pass in the type of that dummy class and it will be parsed.

I don't know why. How can I parse without creating a dummy instance?

  import org.json4s._
  import scala.reflect.runtime._
  import scala.tools.reflect.ToolBox

  implicit val formats = DefaultFormats

  val cm = universe.runtimeMirror(getClass.getClassLoader)
  val toolBox = cm.mkToolBox()

  val parse =
    toolBox.parse(
      s"""
         | case class Person( name:String, age:String)
         | scala.reflect.classTag[ Person].runtimeClass
       """.stripMargin)

  val person = toolBox.compile( parse)().asInstanceOf[Class[_]]
  val dummy  = person.getConstructors.head.newInstance( "a", "b") //make dummy instance

  val js = JsonMethods.parse("""{ "name":"Tom","age" : "28"}""")
  println( js.extract[ dummy.type ] ) // Result: Person(Tom,28)





Aucun commentaire:

Enregistrer un commentaire