Go to the content
or

Debian

 Go back to Planet Debian
Full screen Suggest an article

Norbert Preining: Scala: parse JSON into nested case classes

October 13, 2017 5:24 , by Planet Debian - 0no comments yet | No one following this article yet.
Viewed one time

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]]

Source: https://www.preining.info/blog/2017/10/scala-parse-json-into-nested-case-classes/

0no comments yet

Post a comment

The fields are mandatory.

If you are a registered user, you can login and be automatically recognized.