如果您使用Spray JSON,那麼不處理缺少b
字段的簡單示例將看起來爲l IKE:
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
在噴霧JSON,這可以通過寫入對類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
您是否願意使用其他JSON庫? – mattinbits
是的。我可以使用替代庫。 – talex