From 8616caefdd0533f6735c35ea64f852c75f6e88b1 Mon Sep 17 00:00:00 2001 From: Dmitry Martynov Date: Fri, 22 Apr 2022 18:28:17 -0400 Subject: [PATCH] Move out OptionFormat from StandardFormats to allow mix with custom implicits modules --- .../scala/spray/json/StandardFormats.scala | 26 +++++++++---------- .../scala/spray/json/ProductFormatsSpec.scala | 7 +++++ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/scala/spray/json/StandardFormats.scala b/src/main/scala/spray/json/StandardFormats.scala index d7f499a..8949320 100644 --- a/src/main/scala/spray/json/StandardFormats.scala +++ b/src/main/scala/spray/json/StandardFormats.scala @@ -29,19 +29,6 @@ trait StandardFormats { implicit def optionFormat[T :JF]: JF[Option[T]] = new OptionFormat[T] - class OptionFormat[T :JF] extends JF[Option[T]] { - def write(option: Option[T]) = option match { - case Some(x) => x.toJson - case None => JsNull - } - def read(value: JsValue) = value match { - case JsNull => None - case x => Some(x.convertTo[T]) - } - // allows reading the JSON as a Some (useful in container formats) - def readSome(value: JsValue) = Some(value.convertTo[T]) - } - implicit def eitherFormat[A :JF, B :JF]: JF[Either[A, B]] = new JF[Either[A, B]] { def write(either: Either[A, B]) = either match { case Right(a) => a.toJson @@ -118,3 +105,16 @@ trait StandardFormats { } } + +class OptionFormat[T :JsonFormat] extends JsonFormat[Option[T]] { + def write(option: Option[T]) = option match { + case Some(x) => x.toJson + case None => JsNull + } + def read(value: JsValue) = value match { + case JsNull => None + case x => Some(x.convertTo[T]) + } + // allows reading the JSON as a Some (useful in container formats) + def readSome(value: JsValue) = Some(value.convertTo[T]) +} diff --git a/src/test/scala/spray/json/ProductFormatsSpec.scala b/src/test/scala/spray/json/ProductFormatsSpec.scala index 38596ae..ea89bde 100644 --- a/src/test/scala/spray/json/ProductFormatsSpec.scala +++ b/src/test/scala/spray/json/ProductFormatsSpec.scala @@ -51,6 +51,13 @@ class ProductFormatsSpec extends Specification { "convert to a respective JsObject" in { obj.toJson mustEqual json } + "support another instances module" in { + object MyImplicits extends DefaultJsonProtocol + import MyImplicits.optionFormat + implicit val test2Format: JsonFormat[Test2] = jsonFormat2(Test2) + + Test2(42, None).toJson mustEqual JsObject("a" -> JsNumber(42)) + } "convert a JsObject to the respective case class instance" in { json.convertTo[Test2] mustEqual obj }