Scala JSON Parser

#1

{
“name”: “joe”,
“steps”: [
{
“name”: “sort1”,
“operatorName”: “sort”,
“stepNumber”: 1
},
{
“name”: “join1”,
“operatorName”: “join”,
“primary”: {
“keyname”: “customerID”,
“datatype”: “Int”
}
}
]
}

case class Sort(name :String,operatorName:String,stepNumber:Int )
case class Primary(keyname:String,datatype:Int)
case class Join(name,operatorName,primary:Primary)
case class WorkFlow(name:String,steps:List[Step])

would like to parese the JSON and map the parsed output to the case classes(POJO) so that can consume Objects in my application.
I tried with JSON4S library to achieve the same but could not find to map json parser to the Object

In the sample json “steps” is a list/Array has each element different structure. Would need to iterate through list and based on element(operatorName) type need to map the json parser output to the respective case class. In the given example “steps” array containing “SORT” case class and also “JOIN” case class.

Can you please provide inputs to map json parser output to Object/POJO class based on condition.

Regards,
Sada

1 Like
#2

This is a draft of how you can do it ->

package cs.scala.json.parser.sample

import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods
import org.json4s.jackson.Serialization

case class WorkFlow(name:String, steps:List[Step])
case class Step(name: String, operatorName: String, stepNumber: Option[Int], primary: Option[Primary])
case class Primary(keyname: String, datatype:Int)

object CsScalaJsonParserSampleApp extends App {

      val jsonString = """
        {
          "name": "joe",
          "steps": [
            {
              "name": "sort1",
              "operatorName": "sort",
              "stepNumber": 1
            },
            {
              "name": "join1",
              "operatorName": "join",
              "primary": {
                "keyname": "customerID",
                "datatype": "Int"
              }
            }
          ]
        }"""

      implicit val json4sFormats = DefaultFormats
      
      val workflowFromJson = JsonMethods.parse(jsonString).extract[WorkFlow]

      println(s"Extracted as Scala object: ${workflowFromJson}")

      val newWorkflow = WorkFlow("test", List(Step("step1", "opn1", Some(1), None), Step("step2", "opn2", None, Some(Primary( "kn2", 2)))))

      val newWorkflowAsJson = Serialization.writePretty(newWorkflow) // here you can also use write for getting an slimmer JSON

      println(s"JSON from an Scala object: ${newWorkflowAsJson}")

}

A complete functional SBT project with this can be found at ->