Skip to content

Instantly share code, notes, and snippets.

@vallettea
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save vallettea/f66279dce4837aa7cba0 to your computer and use it in GitHub Desktop.

Select an option

Save vallettea/f66279dce4837aa7cba0 to your computer and use it in GitHub Desktop.
json protocol for spray
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import spray.json._
import spray.json._
scala> import DefaultJsonProtocol._
import DefaultJsonProtocol._
scala> :paste
// Entering paste mode (ctrl-D to finish)
object Foo extends DefaultJsonProtocol {
implicit val fooFormat = jsonFormat1(Foo.apply)
}
case class Foo(bar: String)
// Exiting paste mode, now interpreting.
defined module Foo
defined class Foo
scala> Foo("baz").toJson
res0: spray.json.JsValue = {"bar":"baz"}
package cc.spray.json.example
import cc.spray.json._
object EnumSex extends Enumeration {
type Sex = Value
val MALE = Value("MALE")
val FEMALE = Value("FEMALE")
}
case class Address(no: String, street: String, city: String)
case class Person(name: String, age: Int, sex: EnumSex.Sex, address: Address)
object SprayJsonExamples {
def main(args: Array[String]) {
val json = """{ "no": "A1", "street" : "Main Street", "city" : "Colombo" }"""
val address = JsonParser(json).fromJson[Address]
println(address)
val json2 = """{ "name" : "John", "age" : 26, "sex" : 0 , "address" : { "no": "A1", "street" : "Main Street", "city" : "Colombo" }}"""
val person = JsonParser(json2).fromJson[Person]
println(person)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment