How to convert generic potentially nested map Map[String, Any] to case class using any library in Scala?

后端 未结 3 2116
挽巷
挽巷 2021-01-17 09:27

I\'ve not had much joy with reflection, this answer using shapeless works for some cases (but seems to have many edge cases) Shapeless code to convert Map[String, Any] to ca

3条回答
  •  死守一世寂寞
    2021-01-17 09:43

    Using jackson:

    libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.8"
    libraryDependencies += "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.8"
    
    case class Foo(a: List[Int], b: Option[Double])
    case class Bar(c: Int, d: String, e: Foo)
    
    val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
    println(mapper.convertValue(Map(
      "c" -> 3, 
      "d" -> "foo", 
      "e" -> Map("a" -> List(1, 2))), classOf[Bar]))
    

    Output: Bar(3,foo,Foo(List(1, 2),None))

提交回复
热议问题