LoginSignup
3
2

More than 5 years have passed since last update.

SprayでUUIDをJSONに変換したい

Last updated at Posted at 2014-06-29

spray-jsonを使ってUUIDをJSONに変換する方法。

UUIDのエンコード・デコードの方法のプロトコルを定義する:

UUIDJsonProtocol.scala
import java.util.UUID
import spray.json.deserializationError
import spray.json.{ JsString, JsValue, RootJsonFormat, DefaultJsonProtocol }

object UUIDJsonProtocol extends DefaultJsonProtocol {
  implicit object UuidJsonFormat extends RootJsonFormat[UUID] {
    def write(x: UUID): JsString = JsString(x.toString)
    def read(value: JsValue): UUID = value match {
      case JsString(x) => UUID.fromString(x)
      case x           => deserializationError("Expected UUID as JsString, but got " + x)
    }
  }
}

JSONに変換するサンプルコード:

import java.util.UUID

import spray.json._ // toJsonを使えるようになる
import UUIDJsonProtocol._ // プロトコルを元にコンバートできるようになる

println(UUID.randomUUID.toJson)
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2