Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example doc for enum and case objects #336

Open
wants to merge 1 commit into
base: release/1.3.x
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,86 @@ can enforce the rendering of undefined members as `null`.
(Note that this only affect JSON writing, spray-json will always read missing optional members as well as `null`
optional members as `None`.)

### Providing JsonFormats for enumeration

There isn't an official support for enumeration types, but here a possible implementation example:

```scala
import spray.json._

class EnumJsonFormat[T <: scala.Enumeration](enu: T) extends RootJsonFormat[T#Value] {
Copy link

@waagnermann waagnermann Dec 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the lib owners can't merge this EnumJsonFormat class to make it official?

override def write(obj: T#Value): JsValue = JsString(obj.toString)

override def read(json: JsValue): T#Value = {
json match {
case JsString(txt) => enu.withName(txt)
case somethingElse => throw DeserializationException(s"Expected a value from enum $enu instead of $somethingElse")
}
}
}
```

Usage:

```scala
object Fruits extends Enumeration {
type Fruit = Value
val APPLE, BANANA, MANGO = Value
}

import spray.json._

it("should be possible to serialize/deserialize enum") {
implicit val fruitFormat: EnumJsonFormat[Fruits.type] = new EnumJsonFormat(Fruits)

Fruits.APPLE.toJson should be(JsString("APPLE"))
JsString("BANANA").convertTo[Fruits.Fruit] should be(Fruits.BANANA)
}
```

### Providing JsonFormats for sealed trait of case objects

There isn't an official support for sealed trait of case objects, but here a possible implementation example:

```scala
import spray.json._

import scala.reflect.ClassTag

class CaseObjectJsonFormat[T: ClassTag](values: Seq[T])(implicit tag: ClassTag[T]) extends RootJsonFormat[T] {
/** A mapping from object names to the objects */
private val mapping = values.map(obj => key(obj) -> obj).toMap

override def read(json: JsValue): T = (json match {
case JsString(value) => mapping.get(value)
case _ => None
}).getOrElse(deserializationError(s"Unknown json value found when converting to $tag: $json"))

override def write(value: T): JsValue = JsString(key(value))

private def key(input: T): String = input.getClass.getSimpleName.stripSuffix("$")
}
```

Usage:

```scala
sealed trait Car
object Cars {
val values = Seq(Ferrari, Fiat)
case object Ferrari extends Car
case object Fiat extends Car
}

import spray.json._

it("should be possible to serialize/deserialize case objects") {
implicit val carFormat: CaseObjectJsonFormat[Car] = new CaseObjectJsonFormat(Cars.values)

Cars.Ferrari.asInstanceOf[Car].toJson should be(JsString("Ferrari"))
JsString("Fiat").convertTo[Car] should be(Cars.Fiat)
}
```

### Providing JsonFormats for other Types

Expand Down