如何为Map [String,Any]编写自定义圆圈编解码器

问题描述

是否可以使用circe为Map [String,Any]编写自定义解码器?我已经找到了,但这只是转换为Json:

def mapToJson(map: Map[String,Any]): Json =
    map.mapValues(anyToJson).asJson

  def anyToJson(any: Any): Json = any match {
    case n: Int => n.asJson
    case n: Long => n.asJson
    case n: Double => n.asJson
    case s: String => s.asJson
    case true => true.asJson
    case false => false.asJson
    case null | None => None.asJson
    case list: List[_] => list.map(anyToJson).asJson
    case list: Vector[_] => list.map(anyToJson).asJson
    case Some(any) => anyToJson(any)
    case map: Map[String,Any] => mapToJson(map)
  }

解决方法

import io.circe.syntax.EncoderOps
import io.circe.{Encoder,Json}

case class Person(name: String,age: Int)
object Person {
  implicit val decoder: io.circe.Decoder[Person] = io.circe.generic.semiauto.deriveDecoder
  implicit val encoder: io.circe.Encoder[Person] = io.circe.generic.semiauto.deriveEncoder
}

case class Home(area: Int)
object Home {
  implicit val decoder: io.circe.Decoder[Home] = io.circe.generic.semiauto.deriveDecoder
  implicit val encoder: io.circe.Encoder[Home] = io.circe.generic.semiauto.deriveEncoder
}

def jsonPrinter[A](obj: A)(implicit encoder: Encoder[A]): Json =
    obj.asJson

jsonPrinter(Person("Eminem",30))
jsonPrinter(Home(300))

这是通过泛型完成的,希望对您有帮助

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...