mardi 28 juillet 2015

Getting type from class

I've been working on a project that stores case classes in a database and can take them back out again, storing them works fine but I am having trouble with getting them back out.

For items like Strings, Ints, Floats, etc, are being stored as they are but other types are converted to a JSON string using json4s like so

  private def convertToString(obj: AnyRef, objType: Class[_]): String = {
    implicit val formats = Serialization.formats(NoTypeHints)

    objType match {
      case t if t == classOf[String]      => obj.asInstanceOf[String]
      case t if t == classOf[Int]         => obj.toString
      case t if t == classOf[Integer]     => obj.toString
      case t if t == classOf[Boolean]     => if (obj.asInstanceOf[Boolean]) "true" else "false"
      case t if t == classOf[Short]       => obj.toString
      case t if t == classOf[Double]      => obj.toString
      case t if t == classOf[Long]        => obj.toString
      case t if t == classOf[Float]       => obj.toString
      case t if t == classOf[Byte]        => obj.toString
      case _                              => write(obj)(formats)
    }
  }

This is working fine and store items just like I would expect it to, but the problem is converting the items back from JSON.

Lets say I have the case class Test(testInt: Int, testString: String, testMap: Map[String, _]) and I get the data back as 3,'blablabla','{"Test": "Map"}'

I can put all values into a new instance of the class expect for the map, here is the code I am using

private def restoreTypes(objClass: Class[_], argList: Array[Object]): Array[_ <: Object] = {
    var correctTypes = Array.empty[Object]
    val fields = objClass.getDeclaredFields

    for(i <- 0 until fields.length) {
      val giveType = argList(i).getClass
      val wantedType = fields(i).getType

      if(giveType != wantedType && giveType == classOf[String])
        read[/*HERE*/](argList(i).asInstanceOf[String])
      else
        correctTypes = correctTypes :+ argList(i)
    }

    correctTypes
}

And this method is called list so

objClass.getConstructors()(0).newInstance(restoreTypes(objClass, args): _*)

I am getting stuck on how to pass the wanted type to the read method





Aucun commentaire:

Enregistrer un commentaire