在字段反序列化期间将 Scala JSON4S 转换为 return 三元组
Scala JSON4S to return a triple during field deserialization
我正在使用 JSON4S,当相应对象的字段是一个选项时,它可以正确处理缺失的字段。
我正在使用
implicit val formats =
Serialization.formats(NoTypeHints) +
new org.json4s.ext.EnumNameSerializer(E)
和read[T](json)
.
它是完美的,除了一件事。我想在缺失和 null
字段之间指定。我希望我的 T
的每个字段都有类似 Triple
的东西,而不是 Option
,其中这个三元组可以是 Some(t)
,Missing
或 Nullified
类似于 Option
的工作方式。我在定义这样的结构方面没有问题,但不幸的是我不太熟悉 JSON4S 的工作原理,或者我如何(可能)"intercept" 解析字段以实现这样的值提取。
作为替代方案,如果解析器将 T
的相应字段设置为 null
如果字段是 field: null
而不是将其设置为 None
。我认为这不会让人觉得是 Scalaiish。
您可能应该为 T
实现自定义序列化程序。我会使用以下格式,因为它允许更大的灵活性和 order independent 输入:
import org.json4s.CustomSerializer
import org.json4s.JsonAST._
import org.json4s.JsonDSL._
case class Animal(name: String, nrLegs: Int)
class AnimalSerializer extends CustomSerializer[Animal](format => ( {
case jsonObj: JObject =>
val name = (jsonObj \ "name") //JString
val nrLegs = (jsonObj \ "nrLegs") //JInt
Animal(name.extract[String], nrLegs.extract[Int])
}, {
case animal: Animal =>
("name" -> animal.name) ~
("nrLegs" -> animal.nrLegs)
}
))
要处理 null/empty 值,请查看 JSValue trait。对于空值,您应该匹配 JNull
,对于不存在的值,您应该匹配 JNothing
.
我正在使用 JSON4S,当相应对象的字段是一个选项时,它可以正确处理缺失的字段。 我正在使用
implicit val formats =
Serialization.formats(NoTypeHints) +
new org.json4s.ext.EnumNameSerializer(E)
和read[T](json)
.
它是完美的,除了一件事。我想在缺失和 null
字段之间指定。我希望我的 T
的每个字段都有类似 Triple
的东西,而不是 Option
,其中这个三元组可以是 Some(t)
,Missing
或 Nullified
类似于 Option
的工作方式。我在定义这样的结构方面没有问题,但不幸的是我不太熟悉 JSON4S 的工作原理,或者我如何(可能)"intercept" 解析字段以实现这样的值提取。
作为替代方案,如果解析器将 T
的相应字段设置为 null
如果字段是 field: null
而不是将其设置为 None
。我认为这不会让人觉得是 Scalaiish。
您可能应该为 T
实现自定义序列化程序。我会使用以下格式,因为它允许更大的灵活性和 order independent 输入:
import org.json4s.CustomSerializer
import org.json4s.JsonAST._
import org.json4s.JsonDSL._
case class Animal(name: String, nrLegs: Int)
class AnimalSerializer extends CustomSerializer[Animal](format => ( {
case jsonObj: JObject =>
val name = (jsonObj \ "name") //JString
val nrLegs = (jsonObj \ "nrLegs") //JInt
Animal(name.extract[String], nrLegs.extract[Int])
}, {
case animal: Animal =>
("name" -> animal.name) ~
("nrLegs" -> animal.nrLegs)
}
))
要处理 null/empty 值,请查看 JSValue trait。对于空值,您应该匹配 JNull
,对于不存在的值,您应该匹配 JNothing
.