Created
August 5, 2014 14:46
-
-
Save rhodri/02e8cf0018f11b9e7d05 to your computer and use it in GitHub Desktop.
spray-json format and spray-httpx FromStringDeserializer for Java UUIDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.UUID | |
import spray.httpx.unmarshalling.{FromStringDeserializer, MalformedContent} | |
object UUIDMarshalling { | |
import spray.json._ | |
implicit object UUIDJsonFormat extends JsonFormat[UUID] { | |
def write(uuid: UUID): JsValue = JsString(uuid.toString) | |
def read(json: JsValue): UUID = json match { | |
case JsString(uuidToken) => parseUuidString(uuidToken) match { | |
case None => deserializationError(s"Expected UUID format, got $uuidToken") | |
case Some(uuid) => uuid | |
} | |
case unknown => deserializationError(s"Expected JsString, got $unknown") | |
} | |
} | |
implicit val UUIDFromStringDeserializer = new FromStringDeserializer[UUID] { | |
override def apply(uuidString : String) = parseUuidString(uuidString) match { | |
case Some(uuid) => Right(uuid) | |
case None => Left(MalformedContent(s"Could not parse UUID: $uuidString")) | |
} | |
} | |
private def parseUuidString(token: String): Option[UUID] = { | |
if (token.length != 36) None | |
else try Some(UUID.fromString(token)) | |
catch { | |
case p: IllegalArgumentException => return None | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment