What is a good way to handle default values ​​with a sprayer

In some cases, default values ​​make more sense than options in case classes:

case class Car(numberOfWheels:Int = 4, color:String)

case class Car(numbeOfWheels:Option[Int], color:String) //silly

In the first case, I expect that you can easily convert the following json to an instance:

{"color":"red"}

But with standard jsonFormat2(Car), spray-json complains about the lack of value for numberOfWheels.

How can I get around this most cleanly?

+6
source share
3 answers

I came across the same problem. I created a patch that solves it for me. It makes fields with a default value optional.

https://github.com/spray/spray-json/pull/56

update: PR is updated and remains open https://github.com/spray/spray-json/pull/93

+8
source

, , :

case class Car(numberOfWheels: Int, color: String) {
  def this(color: String) = this(4, color)
}

object Car {
  def apply(color: String) = new Car(color)
}

, jsonFormat1(Car).

+3

The fix I found for the same problem was to implement my own jsonFormat:

implicit object carFormat extends JsonFormat[Car] {
  def write(car: Car): JsObject = {
    val fields = List(
      ("numberOfWheels" -> JsNumber(car.numberOfWheels)),
      ("color" -> JsString(car.color))
    )
    JsObject(fields: _*)
  }

  def read(json: JsValue): Car = {
    val numberOfWheels = fromField[Option[Int]](json, "numberOfWheels")
    val color = fromField[String](json, "color")
    Car(numberOfWheels.getOrElse(4), color)
  }
}
0
source

All Articles