Joe1988
Joe1988

Reputation: 161

Read a JSON and parse the contents and display the result in Scala

I am a newbie in scala. i try to read a json and parse it using json4s library. Already written the case class and code for reading and parsing the sample json file. I need to iterate the json and print the details of each attribute's.

Case Class

case class VehicleDetails(
    name: String,
    manufacturer: String,
    model:  String,
    year:   String,
    color:  String,
    seat:   Int,
    variants: Seq[String],
    engine: Int,
    dealer: Map[String, String],
    franchise:    Map[String, String])

The json data and the code i tried is given below.

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.DefaultFormats


object CarDetails  extends App {

  val json = parse("""{
  "vehicle_details": [
    {
      "CAR": {
        "name": "Brezza",
        "manufacturer": "Maruti",
        "model": "LDI",
        "year": 2019,
        "color": "Blue",
        "seat": 5,
        "engine": 1,
        "cylinder": 4,
        "variants": [
          "LDI",
          "LDI(O)",
          "VDI",
          "VDI(O)",
          "ZDI",
          "ZDI+"
        ],
        "dealer": {
          "kerala": "Popular"
        },
        "franchise": {
          "ekm": "popular_ekm"
        }
      },
      "SUV": {
        "name": "Scross",
        "manufacturer": "Maruti",
        "model": "LDI",
        "year": 2020,
        "color": "Blue",
        "variants": [
          "LDI",
          "VDI",
          "ZDI"
        ],
        "dealer": {
          "kerala": "Popular"
        },
        "franchise": {
          "ekm": "popular_ekm"
        }
      }
    }
  ]
}""")

  implicit val formats = DefaultFormats
  val definition = json.extract[VehicleDetails.Definition]
  val elements = (json \\ "vehicle_details").children

Upvotes: 0

Views: 625

Answers (1)

Tim
Tim

Reputation: 27356

This pretty close, just a few small changes needed.

First, create a class that encapsulates all the JSON data:

case class AllDetails(vehicle_details: List[Map[String, VehicleDetails]])

Then just extract that class from the json

implicit val formats = DefaultFormats

val details = Extraction.extract[AllDetails](json)

With this particular JSON the seat and engine fields are not present in all the records so you need to modify VehicleDetails to make these Option values:

case class VehicleDetails(
  name: String,
  manufacturer: String,
  model: String,
  year: String,
  color: String,
  seat: Option[Int],
  variants: Seq[String],
  engine: Option[Int],
  dealer: Map[String, String],
  franchise: Map[String, String]
)

[ Other values that might be omitted in other records will also need to be Option values ]


You can unpick the result using standard Scala methods. For example

res.vehicle_details.headOption.foreach { cars =>
  val typeNames = cars.keys.mkString(", ")
  println(s"Car types: $typeNames")

  cars.foreach { case (car, details) =>
    println(s"Car type: $car")
    println(s"\tName: ${details.name}")
    val variants = details.variants.mkString("[", ", ", "]")
    println(s"\tVariants: $variants")
  }
}

To get back to the raw JSON, use Serialization:

import org.json4s.jackson.Serialization

val newJson = Serialization.write(res)

println(newJson)

Upvotes: 1

Related Questions