I'm writing method with the following signature:
def foo[A: Marshaller, B: Marshaller](f: A => B) = {...}
The catch is that A
could be Unit
. It makes sense that there should be an already-existing json format for Unit
that converts to and from the empty string, and it also makes sense that it should be trivial to implement such a format even if it doesn't exist. How can I define or import a json format for Unit
like I do for case classes as follows:
implicit val myFormat = jsonFormat4(myCaseClassWithFourFields)
To my knowledge no predefined json format for Unit exists. But you can write your own json format:
import spray.json._
import DefaultJsonProtocol._
implicit object UnitJsonFormat extends JsonFormat[Unit] {
def write(u: Unit) = JsObject()
def read(value: JsValue): Unit = value match {
case JsObject(fields) if fields.isEmpty => Unit
}
}
Using it:
scala> println("").toJson
res0: spray.json.JsValue = {}
scala> res0.convertTo[Unit]
scala>
Update: I'm not sure what you are expecting the json to look like for Unit, please clarify.