From 0a0e09f39567abe3d906f1875fe12287b203b9c6 Mon Sep 17 00:00:00 2001 From: Andrey Tararaksin Date: Mon, 29 Jul 2019 21:21:50 +0300 Subject: [PATCH] Add UUID json format --- .../main/scala/spray/json/BasicFormats.scala | 20 +++++++++++++++++++ .../scala/spray/json/BasicFormatsSpec.scala | 16 +++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/spray-json/shared/src/main/scala/spray/json/BasicFormats.scala b/spray-json/shared/src/main/scala/spray/json/BasicFormats.scala index b62bb1e5..add4b2ac 100644 --- a/spray-json/shared/src/main/scala/spray/json/BasicFormats.scala +++ b/spray-json/shared/src/main/scala/spray/json/BasicFormats.scala @@ -17,6 +17,10 @@ package spray.json +import java.util.UUID + +import scala.util.Try + /** * Provides the JsonFormats for the most important Scala types. */ @@ -136,4 +140,20 @@ trait BasicFormats { case x => deserializationError("Expected Symbol as JsString, but got " + x) } } + + implicit object UUIDJsonFormat extends JsonFormat[UUID] { + def write(x: UUID) = { + require(x ne null) + JsString(x.toString) + } + def read(value: JsValue) = { + def stringToUUID(s: String): UUID = Try(UUID.fromString(s)) + .recover { case t => deserializationError("Expected a valid UUID, but got " + s) } + .get + value match { + case JsString(x) => stringToUUID(x) + case x => deserializationError("Expected UUID as JsString, but got " + x) + } + } + } } diff --git a/spray-json/shared/src/test/scala/spray/json/BasicFormatsSpec.scala b/spray-json/shared/src/test/scala/spray/json/BasicFormatsSpec.scala index e43a9a64..5aa12918 100644 --- a/spray-json/shared/src/test/scala/spray/json/BasicFormatsSpec.scala +++ b/spray-json/shared/src/test/scala/spray/json/BasicFormatsSpec.scala @@ -16,6 +16,8 @@ package spray.json +import java.util.UUID + import org.specs2.mutable._ class BasicFormatsSpec extends Specification with DefaultJsonProtocol { @@ -165,4 +167,18 @@ class BasicFormatsSpec extends Specification with DefaultJsonProtocol { } } + "The UUIDJsonFormat" should { + val good = "833a1d98-031e-4deb-b7cd-0f012c1d7e77" + val bad = "not_a_UUID" + "convert a UUID to a JsString" in { + UUID.fromString(good).toJson mustEqual JsString(good) + } + "convert a JsString to a UUID" in { + JsString(good).convertTo[UUID] mustEqual UUID.fromString(good) + } + "throw an Exception when trying to deserialize an invalid UUID String" in { + JsString(bad).convertTo[UUID] must throwA(new DeserializationException("Expected a valid UUID, but got " + bad)) + } + } + }