diff --git a/modules/core/src/main/scala/tethys/writers/instances/AllJsonWriters.scala b/modules/core/src/main/scala/tethys/writers/instances/AllJsonWriters.scala index b9373ee0..60f10d37 100644 --- a/modules/core/src/main/scala/tethys/writers/instances/AllJsonWriters.scala +++ b/modules/core/src/main/scala/tethys/writers/instances/AllJsonWriters.scala @@ -3,7 +3,7 @@ package tethys.writers.instances import tethys.JsonWriter import tethys.writers.tokens.TokenWriter -trait AllJsonWriters extends OptionWriters { +trait AllJsonWriters extends OptionWriters with EitherWriters { implicit lazy val intWriter: JsonWriter[Int] = new JsonWriter[Int] { override def write(value: Int, tokenWriter: TokenWriter): Unit = tokenWriter.writeNumber(value) } diff --git a/modules/core/src/main/scala/tethys/writers/instances/EitherWriters.scala b/modules/core/src/main/scala/tethys/writers/instances/EitherWriters.scala new file mode 100644 index 00000000..d5bb422b --- /dev/null +++ b/modules/core/src/main/scala/tethys/writers/instances/EitherWriters.scala @@ -0,0 +1,22 @@ +package tethys.writers.instances + +import tethys.JsonWriter +import tethys.writers.tokens.TokenWriter + +private[tethys] trait EitherWriters { + implicit def eitherWriter[L, R](implicit L: JsonWriter[L], R: JsonWriter[R]): JsonWriter[Either[L, R]] = new JsonWriter[Either[L, R]] { + override def write(name: String, value: Either[L, R], tokenWriter: TokenWriter): Unit = { + value match { + case Left(left) => L.write(name, left, tokenWriter) + case Right(right) => R.write(name, right, tokenWriter) + } + } + + def write(value: Either[L, R], tokenWriter: TokenWriter): Unit = { + value match { + case Left(left) => L.write(left, tokenWriter) + case Right(right) => R.write(right, tokenWriter) + } + } + } +} diff --git a/modules/core/src/test/scala/tethys/writers/DefaultWritersTest.scala b/modules/core/src/test/scala/tethys/writers/DefaultWritersTest.scala index 183a0df7..d578ff57 100644 --- a/modules/core/src/test/scala/tethys/writers/DefaultWritersTest.scala +++ b/modules/core/src/test/scala/tethys/writers/DefaultWritersTest.scala @@ -36,6 +36,8 @@ class DefaultWritersTest extends AnyFlatSpec { test(Map("a" -> 1, "b" -> 2)) -> obj("a" -> 1, "b" -> 2), test(Option(1), "Option.nonEmpty") -> value(1), test(Option.empty[Int], "Option.empty") -> List(NullValueNode), + test(Right(1): Either[String, Int], "Either.right") -> value(1), + test(Left("Not an Int"): Either[String, Int], "Either.left") -> value("Not an Int"), test(1: java.lang.Integer) -> value(1), test(java.lang.Short.valueOf(1: Short)) -> value(1: Short), test(1L: java.lang.Long) -> value(1L),