Support Questions

Find answers, ask questions, and share your expertise
Announcements
Celebrating as our community reaches 100,000 members! Thank you!

How to convert json data into case class using scala

avatar
Contributor

Hi,

In my case i need to get feed from json and that need to be streamed via spark - scala, so i need to know how to convert json data into case class using scala.

For example: {"Id":"1","Name":"Babu","Address":"dsfjskkjfs"} to (1,babu,dsfjskkjfs}

1 REPLY 1

avatar

There are several Scala native JSON libraries available (json4s, play-json, circe, as well as others) so there are lots of ways to do this.

With play-json, your solution might look like:

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

val jsonStr = """{"Id":1,"Name":"Babu","Address":"dsfjskkjfs"}"""

Person(id: Int, name: String, address: String)

implicit val personReads: Reads[Person] = (
  (JsPath \ "Id").read[Int] and
  (JsPath \ "Name").read[String] and
  (JsPath \ "Address").read[String]
)(Person.apply _)

jsonStr.validate[Person] match {
  case JsSuccess(person, _) => {
    // do something
  }
  case JsError(e) => {
    // do something
  }
}

With circe, your solution might look like:

import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._

val jsonStr = """{"Id":1,"Name":"Babu","Address":"dsfjskkjfs"}"""

Person(id: Int, name: String, address: String)

decode[Person](jsonStr) match {
  case Right(person) => {
    // do something with Person(1, "Babu", "dsfjskkjfs")
  }
  case Left(e) => {
    // handle error
  }
}

In your question you asked for a case class but wrote it out as a tuple, so just to close that loop, if you want to subsequently convert the data to a tuple you can do `Person.unapply(person).get`.