How to get a simple string encoding for Enumeratum enum in Zio-JSON

489 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.