Skip to content
Open
Show file tree
Hide file tree
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
26 changes: 13 additions & 13 deletions src/main/scala/spray/json/StandardFormats.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,6 @@ trait StandardFormats {

implicit def optionFormat[T :JF]: JF[Option[T]] = new OptionFormat[T]

class OptionFormat[T :JF] extends JF[Option[T]] {
def write(option: Option[T]) = option match {
case Some(x) => x.toJson
case None => JsNull
}
def read(value: JsValue) = value match {
case JsNull => None
case x => Some(x.convertTo[T])
}
// allows reading the JSON as a Some (useful in container formats)
def readSome(value: JsValue) = Some(value.convertTo[T])
}

implicit def eitherFormat[A :JF, B :JF]: JF[Either[A, B]] = new JF[Either[A, B]] {
def write(either: Either[A, B]) = either match {
case Right(a) => a.toJson
Expand Down Expand Up @@ -118,3 +105,16 @@ trait StandardFormats {
}

}

class OptionFormat[T :JsonFormat] extends JsonFormat[Option[T]] {
def write(option: Option[T]) = option match {
case Some(x) => x.toJson
case None => JsNull
}
def read(value: JsValue) = value match {
case JsNull => None
case x => Some(x.convertTo[T])
}
// allows reading the JSON as a Some (useful in container formats)
def readSome(value: JsValue) = Some(value.convertTo[T])
}
7 changes: 7 additions & 0 deletions src/test/scala/spray/json/ProductFormatsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ class ProductFormatsSpec extends Specification {
"convert to a respective JsObject" in {
obj.toJson mustEqual json
}
"support another instances module" in {
object MyImplicits extends DefaultJsonProtocol
import MyImplicits.optionFormat
implicit val test2Format: JsonFormat[Test2] = jsonFormat2(Test2)

Test2(42, None).toJson mustEqual JsObject("a" -> JsNumber(42))
}
"convert a JsObject to the respective case class instance" in {
json.convertTo[Test2] mustEqual obj
}
Expand Down