Created
August 28, 2012 14:11
-
-
Save nisshiee/3498346 to your computer and use it in GitHub Desktop.
lift-jsonのextractで痒いところに手を伸ばす
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
sealed trait Carrier | |
case object PC extends Carrier | |
case object Mobile extends Carrier | |
case object Smartphone extends Carrier |
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 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) | |
} | |
} |
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 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) |
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 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