【问题标题】:Parsing primitive types in Circe在 Circe 中解析原始类型
【发布时间】:2019-09-26 02:11:55
【问题描述】:

当字段可以具有不同的原始值类型时,我遇到了 json 解析问题。比如我可以得到json:

{
  "name" : "john",
  "age" : 31
}

也可以是这样的形式:

{
  "name" : "john",
  "age" : "thirty one"
}

或者这样:

{
  "name" : "john",
  "age" : 31.0
}

我希望能够将字段 age 解析为以下 ADT 实例:

sealed trait PrimitiveWrapper

case class IntWrapper(v: Int) extends PrimitiveWrapper

case class StringWrapper(v: String) extends PrimitiveWrapper

case class FloatWrapper(v: Float) extends PrimitiveWrapper

所以最后我可以得到这样的东西:

case class Person(name: String, age: PrimitiveWrapper)

我该怎么做?我找到了这个话题:How to decode an ADT with circe without disambiguating objects

但在那个解决方案中,我们解析的不是原始字段。

【问题讨论】:

    标签: json scala parsing circe


    【解决方案1】:

    你可以这样做:

    import cats.syntax.functor._
    import io.circe.Decoder, io.circe.generic.auto._
    
    sealed trait PrimitiveWrapper
    
    case class IntWrapper(v: Int) extends PrimitiveWrapper
    
    case class StringWrapper(v: String) extends PrimitiveWrapper
    
    case class FloatWrapper(v: Float) extends PrimitiveWrapper
    
    case class Person(name: String, age: PrimitiveWrapper)
    
    object GenericDerivation {
    
      implicit val decodePrimitiveWrapper: Decoder[PrimitiveWrapper] =
        List[Decoder[PrimitiveWrapper]](
          Decoder.decodeInt.map(IntWrapper).widen,
          Decoder.decodeString.map(StringWrapper).widen,
          Decoder.decodeFloat.map(FloatWrapper).widen
        ).reduceLeft(_ or _)
    
    
      def main(args: Array[String]): Unit = {
        import io.circe.parser.decode
        println(decode[Person]("""{"name" : "john", "age" : 31 }"""))
        println(decode[Person]("""{"name" : "john", "age" : "thirty one" }"""))
        println(decode[Person]("""{"name" : "john", "age" : 31.3 }"""))
        // Prints
        // Right(Person(john,IntWrapper(31)))
        // Right(Person(john,StringWrapper(thirty one)))
        // Right(Person(john,FloatWrapper(31.3)))
      }
    }
    
    

    注意:以下获取解析使用IntWrapper

     println(decode[Person]("""{"name" : "john", "age" : 31.0 }"""))
    

    更新:正如@Travis 指出的decodePrimitiveWrapper 可以这样写:

      implicit val decodePrimitiveWrapper: Decoder[PrimitiveWrapper] =
          Decoder.decodeInt.map(IntWrapper).widen[PrimitiveWrapper] or
            Decoder.decodeString.map(StringWrapper).widen[PrimitiveWrapper] or
            Decoder.decodeFloat.map(FloatWrapper).widen[PrimitiveWrapper]
    

    【讨论】:

    • 我会写出两个ors 而不是减少,否则这就是我要做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2021-06-09
    • 2019-03-15
    • 2019-12-27
    • 2019-11-02
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多