Serialize nested Scala case cass to Json

There are several ways to serialize nested Scala classes to Json, an simple method is by using spray-json. Nested case classes can be serialized as well with few easy steps:

Create case classes

First create the case classes in Scala, for example this News class which contains InstrumentInfo:

File InstrumentInfo.class:
case class InstrumentInfo(instrumentId: String, name: String, symbol: String, ask: Option[Double], bid: Option[Double], lastTradeDate: Option[Long], volume: Option[Long], open: Option[Double], previousClose: Option[Double], marketCapitalization: Option[Long])
File News.scala:
case class News(title: String, body: Option[String], link: String, instruments: List[String], dateTimeUtc: Long, source: String, instrumentsSnapshot: List[InstrumentInfo])

Declare the JSON serializer

Next create the object MyJsonProtocol which defines the serializer. Remember to import the spray-json library in your project to make it work.
import spray.json.DefaultJsonProtocol

object MyJsonProtocol extends DefaultJsonProtocol {
implicit val instrumentInfoFormat = jsonFormat10(InstrumentInfo)
implicit val newsFormat = jsonFormat7(News)

The jsonFormatN function declares the serializer as implicit method, just replace N with the number of the case class member and Scala will do the magic.

Use the method toJson and parseJson

The method toJson will convert the clase class in JSON while parseJson will parse a JSON string into an object. Just remember to import MyJsonProtocol._ and spray.json._ to make those methods available (see NewsTest)

// Remember to import
import MyJsonProtocol._
import spray.json._

// Example code
val jsonString = news.toJson.toString // news is an existing News object
val newsObject = jsonString.parseJson.convertTo[News]

The source code is available at