这里是 spray-json example .这里是 NullOptions特征。
问题是当我声明一个案例类时说
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val some: RootJsonFormat[Some] = jsonFormat2(Some)
}
case class Some (
name:String,
age:Int
)
并且 json 不包含字段,例如:
{
"name":"John"
}
我得到:
java.util.NoSuchElementException: key not found: age
所以我必须添加一个
Option
和 NullOption
像这样的特质:object MyJsonProtocol extends DefaultJsonProtocol with NullOptions {
implicit val some: RootJsonFormat[Some] = jsonFormat2(Some)
}
case class Some (
name:String,
age:Option[Int]
)
一切正常。但我不想有一个所有成员都是
Option
的案例类。 .有没有办法将喷雾 json 解码配置为只设置空值而无需额外的 Option
类型?附言
我理解一般
Option
比空检查更好,但在我的情况下,它只是猴子代码。响应处理期间编码的完整示例是 here
最佳答案
我能想到的唯一方法是通过 read/write
实现您自己的协议(protocol)。 ,这可能很麻烦。下面是一个简化的例子。请注意,我更改了 age
成为 Integer
而不是 Int
自从 Int
是 AnyVal
,默认情况下不可为空。此外,我只考虑 age
字段可以为空,因此您可能需要根据需要采用。希望能帮助到你。
case class Foo (name:String, age: Integer)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit object FooJsonFormat extends RootJsonFormat[Foo] {
def write(foo: Foo) =
JsObject("name" -> JsString(foo.name),
"age" -> Option(foo.age).map(JsNumber(_)).getOrElse(JsNull))
def read(value: JsValue) = value match {
case JsObject(fields) =>
val ageOpt: Option[Integer] = fields.get("age").map(_.toString().toInt) // implicit conversion from Int to Integer
val age: Integer = ageOpt.orNull[Integer]
Foo(fields.get("name").get.toString(), age)
case _ => deserializationError("Foo expected")
}
}
}
import MyJsonProtocol._
import spray.json._
val json = """{ "name": "Meh" }""".parseJson
println(json.convertTo[Foo]) // prints Foo("Meh",null)
关于json - 当 json 元素不存在时,如何设置 spray-json 以设置 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019297/