JSON parsing in Scala
We can use the Spray JSON parser for uses other than a REST API. We add spray-json to our dependencies. Our build.gradle:
apply plugin: 'scala'
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
compile group: 'io.spray', name: 'spray-json_2.11', version: '1.3.1'
}
We add the imports in JsonApp.scala:
import spray.json._
import spray.json.DefaultJsonProtocol._
We define our domain class. Then have an implicit variable in scope to define how it should be formatted:
case class Vegetable(name: String, color: String)
implicit val VegetableFormat = jsonFormat2(Vegetable)
Now we can parse JSON strings to vegetables:
val spinachString = """{"name": "spinach", "color": "green"}"""
val spinach: Vegetable = spinachString.parseJson.convertTo[Vegetable]
Or output vegetables as JSON:
val broccoli = Vegetable("broccoli", "green")
val beet = Vegetable("beet", "red")
println(broccoli.toJson.compactPrint)
println(beet.toJson.prettyPrint)
Result:
{"name":"broccoli","color":"green"}
{
"name": "beet",
"color": "red"
}
The whole App:
import spray.json._
import spray.json.DefaultJsonProtocol._
object JsonApp extends App {
case class Vegetable(name: String, color: String)
implicit val VegetableFormat = jsonFormat2(Vegetable)
val spinachString = """{"name": "spinach", "color": "green"}"""
val spinach: Vegetable = spinachString.parseJson.convertTo[Vegetable]
val broccoli = Vegetable("broccoli", "green")
val beet = Vegetable("beet", "red")
println(broccoli.toJson.compactPrint)
println(beet.toJson.prettyPrint)
}
spray-json documentation: https://github.com/spray/spray-json