`
sillycat
  • 浏览: 2552251 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Spray(4)spray-json

 
阅读更多
Spray(4)spray-json
Installation
It is available from the repository and based on sbt.
"spray repo"         at "http://repo.spray.io/",
"io.spray"            %   "spray-json_2.10"                   % "1.2.3",

Sometimes there is a trailing "cross CrossVersion.full" modifier for SBT 0.12.x

Check my version
>sbt sbt-version
0.12.1

Usage
First of all, Import the packages
import spray.json._
import spray.httpx.SprayJsonSupport

Define the Object
  object EnumSex extends Enumeration {
    type Sex = Value
    val MALE = Value("MALE")
    val FEMALE = Value("FEMALE")
  }

  case class Address(streetNumber: String, street: String, city: String)

  case class Person(userName: String, age: Int, sex: EnumSex.Sex, address: Address)

  case class Color(name: String, red: Int, green: Int, blue: Int)

Then I can parse the string to AST abstract Syntax Tree(AST).

1. String to AST
  valjson1 = """{ "streetNumber": "A1", "street" : "Main Street", "city" : "Colombo" }"""
  valjson2 = """{ "name" : "John", "age" : 26,  "sex" : 0 , "address" : { "streetNumber": "A1", "street" : "Main Street", "city" : "Colombo" }}"""

  //string to AST
  valaddressAST = json1.asJson //or JsonParser(source)
  valpersonAST = json2.asJson

2. AST to String
  //AST to string
  println(addressAST.compactPrint) //or .compactPrint
  println(personAST.prettyPrint)

3. AST to Object
  import AddressJsonProtocol._
  //AST 2 Object
  val address1 = addressAST.convertTo[Address]

4. Object to AST
  //Object 2 AST
  valaddressAST2 = address1.toJson

Some other examples:
  import ColorProtocol._
  //Object 2 AST
  val colorAST = Color("CadetBlue", 95, 158, 160).toJson

  //AST 2 Object
  val color1 = colorAST.convertTo[Color]

For the step3 and step4, we can not directly use that. We need to implement and import the DefaultJsonProtocol.

  object ColorProtocol extends DefaultJsonProtocol {
    implicit val colorFormat = jsonFormat4(Color)
  }

  object AddressJsonProtocol extends DefaultJsonProtocol with SprayJsonSupport {
    implicit object AddressJsonFormat extends RootJsonFormat[Address] {
      def write(address: Address) = JsObject(
        "streetNumber" -> JsString(address.streetNumber),
        "street" -> JsString(address.street),
        "city" -> JsString(address.city))
      def read(jsAddress: JsValue) = {
        jsAddress.asJsObject.getFields("streetNumber", "street", "city") match {
          case Seq(JsString(streetNumber), JsString(street), JsString(city)) =>
            new Address(streetNumber, street, city)
          case _ => throw new DeserializationException("Address expected")
        }
      }
    }
  }

References:
https://github.com/spray/spray-json
https://github.com/jestan/spray-json-examples
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics