Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import io.circe.Decoder.Result
- import io.circe._
- trait Codecs {
- implicit val mapEncoder = new Encoder[Map[String, Any]] {
- override def apply(obj: Map[String, Any]): Json = {
- def convert(arg: Any): Json = {
- arg match {
- case x: Int => Json.fromInt(x)
- case x: Long => Json.fromLong(x)
- case x: Float => Json.fromFloat(x).getOrElse(Json.fromInt(0))
- case x: Double => Json.fromDouble(x).getOrElse(Json.fromInt(0))
- case x: String => Json.fromString(x)
- case x: Boolean => Json.fromBoolean(x)
- case x: Map[String @unchecked, Any @unchecked] => Json.fromFields(x mapValues convert)
- case x: Iterable[Any] => Json.fromValues(x map convert)
- case x: Any => Json.fromString(x.toString)
- }
- }
- Json.fromFields(obj mapValues convert)
- }
- }
- implicit val mapDecoder = new Decoder[Map[String, Any]] {
- import cats.implicits._
- override def apply(c: HCursor): Result[Map[String, Any]] = {
- val keys = c.keys.getOrElse(Nil).toList
- for {
- jsonList <- keys traverse {key => c.downField(key).as[Json]}
- } yield keys.zip(jsonList).toMap
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement