I'm studying the library zio-kafka
, and I want to use zio-json
to deserialize messages' values in JSON format.
I have a simple case class together with its decoder and encoder:
case class Player(name: String, score: Int)
object Player {
implicit val decoder: JsonDecoder[Player] = DeriveJsonDecoder.gen[Player]
implicit val encoder: JsonEncoder[Player] = DeriveJsonEncoder.gen[Player]
}
Right now, I created a Serde
starting from a Serde.string
that uses the above decoder / encoder:
val playerSerde: Serde[Any, Player] = Serde.string.inmapM { playerAsString =>
ZIO.fromEither(playerAsString.fromJson[Player].left.map(new RuntimeException(_)))
} { playerAsObj =>
ZIO.effect(playerAsObj.toJson)
}
Is it correct? Is there any other (better) approach?
Consider using
.getOrElse
as I think it makes the intent a bit clearer and avoids a naked access to the left field:I also assumed that you meant
.fromJson[Player]
as I didn't see aMatch
class anywhere in your question.