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 UUID json format #313

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions spray-json/shared/src/main/scala/spray/json/BasicFormats.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@

package spray.json

import java.util.UUID

import scala.util.Try

/**
* Provides the JsonFormats for the most important Scala types.
*/
Expand Down Expand Up @@ -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)
}
}
}
}
16 changes: 16 additions & 0 deletions spray-json/shared/src/test/scala/spray/json/BasicFormatsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package spray.json

import java.util.UUID

import org.specs2.mutable._

class BasicFormatsSpec extends Specification with DefaultJsonProtocol {
Expand Down Expand Up @@ -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))
}
}

}