How can I transform a Map to a case class in Scala?

后端 未结 5 1853
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 21:00

If I have a Map[String,String](\"url\" -> \"xxx\", \"title\" -> \"yyy\"), is there an way to generically transform it into a case class Image(url:St

5条回答
  •  猫巷女王i
    2020-12-13 21:19

    You can transform map to json and then to case class. It's a bit hacky though.

    import spray.json._
    
    object MainClass2 extends App {
      val mapData: Map[Any, Any] =
        Map(
          "one" -> "1",
          "two" -> 2,
          "three" -> 12323232123887L,
          "four" -> 4.4,
          "five" -> false
        )
    
      implicit object AnyJsonFormat extends JsonFormat[Any] {
        def write(x: Any): JsValue = x match {
          case int: Int           => JsNumber(int)
          case long: Long          => JsNumber(long)
          case double: Double        => JsNumber(double)
          case string: String        => JsString(string)
          case boolean: Boolean if boolean  => JsTrue
          case boolean: Boolean if !boolean => JsFalse
        }
        def read(value: JsValue): Any = value match {
          case JsNumber(int) => int.intValue()
          case JsNumber(long) => long.longValue()
          case JsNumber(double) => double.doubleValue()
          case JsString(string) => string
          case JsTrue      => true
          case JsFalse     => false
        }
      }
    
      import ObjJsonProtocol._
      val json = mapData.toJson
      val result: TestObj = json.convertTo[TestObj]
      println(result)
    
    }
    
    final case class TestObj(one: String, two: Int, three: Long, four: Double, five: Boolean)
    
    object ObjJsonProtocol extends DefaultJsonProtocol {
      implicit val objFormat: RootJsonFormat[TestObj] = jsonFormat5(TestObj)
    }
    

    and use this dependency in sbt build:

     "io.spray"          %%   "spray-json"     %   "1.3.3"
    

提交回复
热议问题