I want to convert a Map[String, Any]
to a given case class, and the map can be a nested map. For example, personDataMap
should be converted into Person("evan",24,Address(15213,"5000 Forbes Ave"))
case class Address(zip: Int, name: String)
case class Person(name: String, age: Int, addr: Address)
val addrDataMap = Map("zip" -> 15213, "name" -> "5000 Forbes Ave")
val personDataMap = Map("name" -> "evan", "age" -> 24, "addr" -> addrDataMap)
The code that converts Map[String, Any]
to non-nested case class can be found below:
import com.twitter.util.{Return, Try}
import scala.reflect._
import scala.reflect.runtime.universe._
// Magic from https://stackoverflow.com/a/24100624/7550592
// Convert a Map[String, _] to a given case class CC
class CaseClassDataMapConverter[CC <: Product] {
def fromMap(dataMap: Map[String, Any])(implicit tt: TypeTag[CC]): Try[CC] = {
val tClassSymbol = typeOf[CC].typeSymbol.asClass
val rm = typeTag[CC].mirror
val classMirror = rm.reflectClass(tClassSymbol)
val constructor = typeOf[CC].decl(termNames.CONSTRUCTOR).asMethod
val constructorMirror = classMirror.reflectConstructor(constructor)
val constructorTries = constructor.paramLists.flatten.map { param: Symbol =>
val paramName = param.name.toString
val tryResult: Try[Any] =
if (param.typeSignature <:< typeOf[Option[Any]]) {
Return(dataMap.get(paramName))
}
else {
Try(dataMap.getOrElse(paramName, new Exception("Param " + paramName + " not found")))
}
println("paramName = " + paramName + ", result = " + tryResult + ", type = " + param.typeSignature)
tryResult
}
Try.collect(constructorTries).flatMap { constructorArgs =>
Try(constructorMirror(constructorArgs: _*).asInstanceOf[CC])
}
}
}
case class Address(zip: Int, name: String)
case class Person(name: String, age: Int, addr: Address)
val converter = new CaseClassDataMapConverter[Person]()
val addrDataMap = Map("zip" -> 15213, "name" -> "5000 Forbes Ave")
val addrTry = fromMap[Address](addrDataMap) // Return(Address(15213,"5000 Forbes Ave"))
val addr = addrTry.get
val personDataMap = Map("name" -> "evan", "age" -> 24, "addr" -> addr)
val personTry = converter.fromMap(personDataMap) // Return(Person(evan,24,Address(15213,5000 Forbes Ave)))
val person = personTry.get
To deal with nested case class, I check param.typeSignature
. If it is a case class (Product
), I convert its value (i.e., a nested Map
) into a case class first. I add a else-if
branch and change personDataMap.addr
to consume a Map
rather than a already made case class:
import com.twitter.util.{Return, Try}
import scala.reflect._
import scala.reflect.runtime.universe._
// Magic from https://stackoverflow.com/a/24100624/7550592
// Convert a Map[String, _] to a given case class CC
class CaseClassDataMapConverter[CC <: Product] {
def fromMap(dataMap: Map[String, Any])(implicit tt: TypeTag[CC]): Try[CC] = {
val tClassSymbol = typeOf[CC].typeSymbol.asClass
val rm = typeTag[CC].mirror
val classMirror = rm.reflectClass(tClassSymbol)
val constructor = typeOf[CC].decl(termNames.CONSTRUCTOR).asMethod
val constructorMirror = classMirror.reflectConstructor(constructor)
val constructorTries = constructor.paramLists.flatten.map { param: Symbol =>
val paramName = param.name.toString
val tryResult: Try[Any] =
if (param.typeSignature <:< typeOf[Option[Any]]) {
Return(dataMap.get(paramName))
}
// Need to deal with: type=Address, result=Map(...)
else if (param.typeSignature <:< typeOf[Product]) {
val nestedDataMap = dataMap.getOrElse(paramName, new Exception("Param " + paramName + " not found"))
val nestedConverter = new CaseClassDataMapConverter[param]()
nestedConverter.fromMap(nestedDataMap)
}
else {
Try(dataMap.getOrElse(paramName, new Exception("Param " + paramName + " not found")))
}
println("paramName = " + paramName + ", result = " + tryResult + ", type = " + param.typeSignature)
tryResult
}
Try.collect(constructorTries).flatMap { constructorArgs =>
Try(constructorMirror(constructorArgs: _*).asInstanceOf[CC])
}
}
}
case class Address(zip: Int, name: String)
case class Person(name: String, age: Int, addr: Address)
val converter = new CaseClassDataMapConverter[Person]()
val addrDataMap = Map("zip" -> 15213, "name" -> "5000 Forbes Ave")
val personDataMap = Map("name" -> "evan", "age" -> 24, "addr" -> addrDataMap)
val personTry = converter.fromMap(personDataMap) // Return(Person(evan,24,Address(15213,5000 Forbes Ave)))
val person = personTry.get
Not surprisingly, it complains:
error: not found: type param
val nestedConverter = new CaseClassDataMapConverter[param]()
My question: is it possible to get a new CaseClassDataMapConverter
with type parameter Address
in this case? If so, what to do? Thanks!
FYI: run environment is scala console.