Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Annotation to treat Either like some sort of "Union" #773

Open
BalduinLandolt opened this issue Oct 27, 2022 · 1 comment
Open

Add Annotation to treat Either like some sort of "Union" #773

BalduinLandolt opened this issue Oct 27, 2022 · 1 comment

Comments

@BalduinLandolt
Copy link
Contributor

Maybe I'm missing something and there is already a (much better) way to do this...
But when using Either, the JSON serialization does not do what I was hoping for:

The following simple script

import zio._
import zio.json._

final case class Something(
    value: Either[String, Int]
)
object Something {
  implicit val codec: JsonCodec[Something] = DeriveJsonCodec.gen[Something]
}

object MyApp extends ZIOAppDefault {
  def run = for {
    _ <- ZIO.unit
    s  = Something(Left("foo"))
    _ <- Console.printLine(s.toJson)
    i  = Something(Right(42))
    _ <- Console.printLine(i.toJson)
  } yield ()
}

prints:

{"value":{"Left":"foo"}}
{"value":{"Right":42}}

Whereas I was actually hoping to get something more like

{"value":"foo"}
{"value":42}

Of course the same goes for decoding.

If there is already a good way to achieve this, I'd be happy to know.
If not, I've been thinking that it could be an option to have an annotation to get this behaviour if wanted. Something along the lines of:

final case class Something(
    @jsonEitherAsUnion(true)
    value: Either[String, Int]
)
object Something {
  implicit val codec: JsonCodec[Something] = DeriveJsonCodec.gen[Something]
}

(I'm sure one could come up with a smarter name for it...)

What do you guys think? And if so, could that be something for the hackathon?

@hardlianotion
Copy link

(Many months after the fact ...)

Could you use the mapping functionality to get what you want as a manual step in either direction?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants