Scala: convert map to case class

Viewed 33707

Let's say I have this example case class

case class Test(key1: Int, key2: String, key3: String)

And I have a map

myMap = Map("k1" -> 1, "k2" -> "val2", "k3" -> "val3")

I need to convert this map to my case class in several places of the code, something like this:

myMap.asInstanceOf[Test]

What would be the easiest way of doing that? Can I somehow use implicit for this?

6 Answers

This works well for me,if you use jackson for scala:

def from[T](map: Map[String, Any])(implicit m: Manifest[T]): T = {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.convertValue(map)
}

Reference from:Convert a Map<String, String> to a POJO

Related