If you use Spray JSON, then a simple example which doesn't handle the absence of the b
field would look like:
import spray.json._
case class A(b: Seq[String])
object Protocol extends DefaultJsonProtocol {
implicit def aFormat = jsonFormat1(A)
}
import Protocol._
val str1 = """{ "b" : [] }""""
val str2 = """{ "b" : ["a", "b", "c"] }""""
val str3 = """{}"""
str1.parseJson.convertTo[A]//successful
str2.parseJson.convertTo[A]//successful
str3.parseJson.convertTo[A]//Deserialization error
In Spray JSON, this can be solved by writing a more detailed protocol format for class A:
import spray.json._
case class A(b: Seq[String])
object Protocol extends DefaultJsonProtocol {
implicit object aFormat extends RootJsonFormat[A] {
override def write(obj: A): JsValue = JsObject("b" -> obj.b.toJson)
override def read(json: JsValue): A = json match {
//Case where the object has exactly one member, 'b'
case JsObject(map) if map.contains("b") && map.size == 1 => A(map("b").convertTo[Seq[String]])
//Case where the object has no members
case JsObject(map) if map.isEmpty => A(Seq())
//Any other json value, which cannot be converted to an instance of A
case _ => deserializationError("Malformed")
}
}
}
import Protocol._
val str1 = """{ "b" : [] }""""
val str2 = """{ "b" : ["a", "b", "c"] }""""
val str3 = """{}"""
str1.parseJson.convertTo[A]//successful
str2.parseJson.convertTo[A]//successful
str3.parseJson.convertTo[A]//successful