jonderry
jonderry

Reputation: 23633

Spray json format for Unit type

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)

Upvotes: 1

Views: 877

Answers (2)

mukesh210
mukesh210

Reputation: 2892

I came to this question and later found out that spray provides JsonFormats for the most important Scala Types(e.g. Int, Long, Float, Double, Byte, Short, BigDecimal, BigInt, Unit, Boolean, Char, String and Symbol) in trait BasicFormats.

You can simply mixin BasicFormats and it will work.

Upvotes: 0

Christian
Christian

Reputation: 4593

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.

Upvotes: 2

Related Questions