HknLof HknLof - 23 days ago 6x
JSON Question

Scala PlayFramework: Merge two Seq's of different Models and create a JSON write

I'm looking for an elegant way to create an JSON from the following scenario:

Assuming I have two case classes as models

case class PersonModel(id: Int, name: String)
case class CarModel(id: Int, model: CarModel)

After querying my database I retrieve a Seq[PersonModel] and Seq[CarModel]. I want to write both sequences into a single JSON Array of the following Structure:

[{Person1}, {Car1}, {Person2}, {Person3}, {Car3}]

So sorting all elements by their id and then writing them into a single array is what I want to do. How do experienced scala/play users go about it?

My Solution is a bit clumsy, as I lose type information. First I convert the Cars to Persons.

implicit def convert cars2Persons(car: CarModel) =
PersonModel(id =, name = car.model)

Afterwards I do String checks on my


This looks like a classic use case for existential types.

You can provide an existential type parameter as T forSome {type T}

import scala.language.existentials
import play.libs.json._

case class Person(id: Int, name: String)
case class Car(id: Int, model: String)

implicit val personFormat = Json.format[Person]
implicit val carFormat = Json.format[Car]

val listOfCars = List(
  Car(id = 1, model = "Tardis"),
  Car(id = 2, model = "Tardis"),
  Car(id = 3, model = "Tardis"),
  Car(id = 4, model = "Tardis")

val listOfPersons = List(
  Person(id = 1, name = "The Doctor"),
  Person(id = 2, name = "The New Doctor"),
  Person(id = 3, name = "The All New Doctor")

val list = List.empty[T forSome {type T}] ++ listOfPersons ++ listOfCars

val sortedList = list.sortBy({
  case Person(id, name) => id
  case Car(id, model) => id

val json = Json.toJson(sortedList)

val jsonString = Json.stringify(json)