New to Scala and Play and running into a problem where I have the following:
case class Media(
name: String,
id: Id,
type: String,
properties: PodcastProperties
)
object Media {
implicit val format: OFormat[Media] = Json.format[Media]
case class PodcastProperties(
x: Int,
y: DateTime,
z: String
)
object PodcastProperties {
implicit val format: OFormat[PodcastProperties] = Json.format[PodcastProperties]
Say I want to define Media to accept different media types. Let's say I have a Json Media object, and it's type is "newspaper" and it's properties should be parse using "NewspaperProperties"
case class NewspaperProperties(
Title: String,
Publisher: String
)
object NewspaperProperties {
implicit val format: OFormat[NewspaperProperties] = Json.format[NewspaperProperties]
How can I define Media, so it can parse the "type" field, and then read the "properties" field correctly using the right Json parser?
You need to defined the media properties as sealed family.
Then a
OFormat
can be materialized forMediaProperties
.This managed discriminator in the JSON representation (by default
_type
field, naming can be configured).Then the format for
Media
can be materialized automatically.