by shigemk2

当面は技術的なことしか書かない

spray-jsonについて

SprayでJSONを取り扱うライブラリ。

$ sbt console
scala> import spray.json._
import spray.json._
scala> import DefaultJsonProtocol._ // if you don't supply your own Protocol (see below)
import DefaultJsonProtocol._
scala> // Parse a JSON string into its Abstract Syntax Tree (AST) representation
scala> val source = """{ "some": "JSON source" }"""
source: String = { "some": "JSON source" }
scala> val jsonAst = source.parseJson // or JsonParser(source)
jsonAst: spray.json.JsValue = {"some":"JSON source"}
scala> // Convert any Scala object to a JSON AST using the pimped toJson method
scala> val jsonAst = List(1, 2, 3).toJson
jsonAst: spray.json.JsValue = [1,2,3]
scala> // case class
scala> case class Color(name: String, red: Int, green: Int, blue: Int)
defined class Color
scala> object MyJsonProtocol extends DefaultJsonProtocol {
     |   implicit val colorFormat = jsonFormat4(Color)
     | }
defined object MyJsonProtocol
scala> import MyJsonProtocol._
import MyJsonProtocol._
scala> import spray.json._
import spray.json._
scala> val json = Color("CadetBlue", 95, 158, 160).toJson
json: spray.json.JsValue = {"name":"CadetBlue","red":95,"green":158,"blue":160}
scala> val color = json.convertTo[Color]
color: Color = Color(CadetBlue,95,158,160)

jsonFormatがキモ。

github.com