Circe and Scala's Enumeration type

前端 未结 2 1915
无人共我
无人共我 2021-02-14 08:49

I\'m trying to wrap my head around Circe.

So, here\'s the model I\'ve been given:

object Gender extends Enumeration {
     type Gender = Value
     val M         


        
相关标签:
2条回答
  • 2021-02-14 09:48

    Try defining your own encoders and decoders for the enum using:

    Decoder.enumDecoder[E <: Enumeration](enum: E)
    Encoder.enumEncoder[E <: Enumeration](enum: E)
    

    something like:

    object JsonProtocol {
      implicit val genderDecoder: Decoder[Gender.Value] = Decoder.enumDecoder(Gender)
      implicit val genderEncoder: Encoder[Gender.Value] = Encoder.enumEncoder(Gender)
      implicit val productDecoder: Decoder[Product] = deriveDecoder
      implicit val productEncoder: Encoder[Product] = deriveEncoder
    }
    

    These are needed because the automatic/semiautomatic derivers only work for hierarchies of sealed traits and case classes as far as I know. The reason you see that error is because the derived codecs for Product will implicitly require encoders/decoders for the types of each of it's parameters. An encoder/decoder for String is a standard part of Circe, but you'll probably need to create ones for your own enumerations.

    0 讨论(0)
  • 2021-02-14 09:48

    Have a look at enumeratum if you want to use enumerations with circe. You could then try something like this:

    import enumeratum._
    
    sealed trait Gender extends EnumEntry
    
    case object Gender extends CirceEnum[Gender] with Enum[Gender] {
    
      case object Male extends Gender
      case object Female extends Gender
      case object Unisex extends Gender
      case object Unknown extends Gender
    
      val values = findValues
    }
    
    Gender.values.foreach { gender =>
        assert(gender.asJson == Json.fromString(gender.entryName))
    }
    

    This should work with circe's automatic derivation for use with your case classes.

    0 讨论(0)
提交回复
热议问题