user5407287 user5407287 - 2 years ago 113
JSON Question

Reads/Writes/Formats for Non Case Class in Scala

I know how to serialize a case class in Scala with the simple

implicit val caseClassFormat = Json.format[CaseClass]

However, I can't seem to find how to serialize a regular class. How does this work? I know that I have to extend Serializable. But, then when I try to run
my compiler throws an error saying that I need to write an implicit reads/writes.

Any and all help would be appreciated. Thanks.

Answer Source

The Json.format[X] call runs a macro in play that creates the Format[X] code for you.

If you look at the implementation of the Macro, it requires that an unapply and apply function exist within the companion object of the class that is provided. With a case class, both of these things are true.

If you want to be able to use the shorthand for formatters, then you can do the following:

import play.api.libs.json.Json

class Foo(val s: String)

object Foo{
  def apply(s: String) = new Foo(s)
  def unapply(f: Foo) = Some(f.s)

val format = Json.format[Foo]

This will allow you to serialize, deserialize the JSON accordingly.

val asString = Json.toJson(Foo("hello"))(format).toString
val js = Json.parse(asString).as[Foo](format)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download