Skip to content

Instantly share code, notes, and snippets.

@nisshiee
Created August 28, 2012 14:11
Show Gist options
  • Save nisshiee/3498346 to your computer and use it in GitHub Desktop.
Save nisshiee/3498346 to your computer and use it in GitHub Desktop.
lift-jsonのextractで痒いところに手を伸ばす
sealed trait Carrier
case object PC extends Carrier
case object Mobile extends Carrier
case object Smartphone extends Carrier
import net.liftweb.json._
lazy val CarrierSerializer = new Serializer[Carrier] {
override def deserialize(implicit format: Formats) = {
case (TypeInfo(c, _), JInt(i)) if c == classOf[Carrier] && i == 0 => PC
case (TypeInfo(c, _), JInt(i)) if c == classOf[Carrier] && i == 1 => Mobile
case (TypeInfo(c, _), JInt(i)) if c == classOf[Carrier] && i == 2 => Smartphone
}
override def serialize(implicit format: Formats) = {
case PC => JInt(0)
case Mobile => JInt(1)
case Smartphone => JInt(2)
}
}
import net.liftweb.json._
val jsonStr = """[0, 1, 2]"""
implicit lazy val myformats = DefaultFormats + CarrierSerializer // 自作Serializerの組み込み
val result = parse(jsonStr).extract[List[Carrier]] // List(PC, Mobile, Smartphone)
import net.liftweb.json._
val arrange: PartialFunction[JValue, JValue] = {
case JObject(List(JField("Item", item))) => item
case JField("Items", items) => JField("items", items)
}
def extract(jsonStr: String) =
parse(jsonStr)
.transform(arrange)
.extract[Result]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment