bugdebug
bugdebug

Reputation: 23

Converting case class object to json string using spray json

I am new to scala and I need to convert a case class object to a json string using spray json. The case class look as below:

case class DriverDetails(userId : String, names : Option[List[String]], addresses : Option[List[Address]], invalidData : Option[Map[String, Map[String, List[String]]]], vehicleIds : List[String])

case class Address(street : Option[String], city : String, state : String, contactNumbers : List[String])

can someone please suggest how to convert the object of case class DriverDetails to json string?

Upvotes: 0

Views: 547

Answers (1)

Saeid Dadkhah
Saeid Dadkhah

Reputation: 363

Spray needs to know the format of the objects to serialize/deserialize them, so you should provide the formats. You can use helper functions to create format for the case classes:

import spray.json.DefaultJsonProtocol._
import spray.json._
implicit val addressFormat: RootJsonFormat[Address] = jsonFormat4(Address)
implicit val driverDetailsFormat: RootJsonFormat[DriverDetails] = 
jsonFormat5(DriverDetails)

Now, you can use toJson function:

val driverDetails = DriverDetails("u", None, Some(List(Address(None, "c", "s", List.empty))), None, List.empty)
val json = driverDetails.toJson
println(json.prettyPrint)

Upvotes: 0

Related Questions