1

So lets say I have a simple enumeratum based enum.

  import enumeratum._


  sealed trait Fruit extends EnumEntry

  object Fruit extends Enum[Fruit] {
    override val values: IndexedSeq[Fruit] = findValues
    case object Avocado extends Fruit
    case object Banana  extends Fruit
    case object Tomato  extends Fruit
  }

And using zio-json I want it to be encoded and decoded in JSON like this:

someObject: {
  ...
  fruit: "Banana"
  ...
}

What is a simple and clean way to do this?

Gaël J
  • 11,274
  • 4
  • 17
  • 32
Peter Lamberg
  • 8,151
  • 3
  • 55
  • 69

1 Answers1

0

Specify a zio-json codec like this:

  implicit val fruitCodec: JsonCodec[Fruit] = JsonCodec[Fruit](
    JsonEncoder[String].contramap[Fruit](_.entryName),
    JsonDecoder[String].mapOrFail(name => Fruit.withNameEither(name).left.map(error => error.getMessage)),
  )

I got the idea from this comment in a zio-json issue.

Peter Lamberg
  • 8,151
  • 3
  • 55
  • 69