Advertisement
mitrakov

Circe Codecs for Map[String, Any]

Jun 3rd, 2019
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.19 KB | None | 0 0
  1. import io.circe.Decoder.Result
  2. import io.circe._
  3.  
  4. trait Codecs {
  5.   implicit val mapEncoder = new Encoder[Map[String, Any]] {
  6.     override def apply(obj: Map[String, Any]): Json = {
  7.       def convert(arg: Any): Json = {
  8.         arg match {
  9.           case x: Int => Json.fromInt(x)
  10.           case x: Long => Json.fromLong(x)
  11.           case x: Float => Json.fromFloat(x).getOrElse(Json.fromInt(0))
  12.           case x: Double => Json.fromDouble(x).getOrElse(Json.fromInt(0))
  13.           case x: String => Json.fromString(x)
  14.           case x: Boolean => Json.fromBoolean(x)
  15.           case x: Map[String @unchecked, Any @unchecked] => Json.fromFields(x mapValues convert)
  16.           case x: Iterable[Any] => Json.fromValues(x map convert)
  17.           case x: Any => Json.fromString(x.toString)
  18.         }
  19.       }
  20.  
  21.       Json.fromFields(obj mapValues convert)
  22.     }
  23.   }
  24.  
  25.   implicit val mapDecoder = new Decoder[Map[String, Any]] {
  26.     import cats.implicits._
  27.     override def apply(c: HCursor): Result[Map[String, Any]] = {
  28.       val keys = c.keys.getOrElse(Nil).toList
  29.       for {
  30.         jsonList <- keys traverse {key => c.downField(key).as[Json]}
  31.       } yield keys.zip(jsonList).toMap
  32.     }
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement