Scala: parse JSON into nested case classes
I was playing around with parsing JSON in Scala, and got spray-json as recommendation from my Senpai. My aim was parsing some nested structure like:
{
"key1" : "value1",
"key2" : { "subkey1" : "subval1", "subkey2" : "subval2" }
}
into a nested Scala case class:
case class SubClass(subkey1: String, subkey2: String)
case class MainClass(key1: String, key2: SubClass)
To achieve this one needs to define one’s own JsonProtocol that describes the parsing:
import spray.json._
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val subclassFormat = jsonFormat2(SubClass)
implicit val mainclassFormat = jsonFormat2(MainClass)
}
import MyJsonProtocol._
Using this parsing can be done in the usual way:
val jsonstr = """
{
"key1" : "value1",
"key2" : { "subkey1" : "subval1", "subkey2" : "subval2" }
}
"""
val jsonAst = jsonstr.parseJson
val gotit = jsonAst.convertTo[MainClass]
If the input is from a JSON array of the above arrays:
[
{
"key1" : "value1",
"key2" : { "subkey1" : "subval1", "subkey2" : "subval2" }
},
{
"key1" : "value10",
"key2" : { "subkey1" : "subval10", "subkey2" : "subval20" }
}
]
the only change necessary is to call
val gotit = jsonAst.convertTo[List[MainClass]]