使用 Circe 在 Scala 中将空值映射到 None
Map null values to None in Scala using Circe
作为此 的延续,我有以下代码,但想将 null
JSON 值映射到 Scala None。我得到的当前行为是,包含 key
和 null
("key": null)
与不包含它之间没有区别。我想将它映射到 None
,这样我就可以将数据库条目设置为 null
。此外,当 key
未包含在 JSON 中时,将其映射到现有值。
import io.circe.jawn.decode, io.circe.generic.auto._
case class Person(name: String, age: Int, description: Option[String])
val existingPerson = Person("mr complete", 42, Some("tall and fat"))
val incompletePersonJson = """{"description":null}"""
val update = decode[Person => Person](incompletePersonJson)
然后:
scala> println(update.map(_(existingPerson)))
Right(Person(mr updated,42,Some(tall and fat)))
但我想得到:
Right(Person(mr updated,42,None))
我最终得到了以下解决方案,它可能并不理想而且它没有使用 Circe,但它为我完成了工作:
def getJsonNullKeys(json: Json): List[String] = {
json.asObject match {
case Some(jsonObject) => jsonObject.filter(j => j._2.isNull).keys.toList
case None => List[String]()
}
}
if (update.isRight) {
update.right.map(_(existingPerson)) match {
case Right(updatedPerson) =>
getNullKeys(incompletePersonJson).foreach { key =>
val field = existingPerson.getClass.getDeclaredField(key)
field.setAccessible(true)
field.set(updatedUpdate, None)
}
println(updatedUpdate)
// outputs Person(mr updated,42,None)
case Left(error) => println(error.toString)
}
}
希望 Circe 添加对此的支持,以便删除所有这些样板文件。
作为此 null
JSON 值映射到 Scala None。我得到的当前行为是,包含 key
和 null
("key": null)
与不包含它之间没有区别。我想将它映射到 None
,这样我就可以将数据库条目设置为 null
。此外,当 key
未包含在 JSON 中时,将其映射到现有值。
import io.circe.jawn.decode, io.circe.generic.auto._
case class Person(name: String, age: Int, description: Option[String])
val existingPerson = Person("mr complete", 42, Some("tall and fat"))
val incompletePersonJson = """{"description":null}"""
val update = decode[Person => Person](incompletePersonJson)
然后:
scala> println(update.map(_(existingPerson)))
Right(Person(mr updated,42,Some(tall and fat)))
但我想得到:
Right(Person(mr updated,42,None))
我最终得到了以下解决方案,它可能并不理想而且它没有使用 Circe,但它为我完成了工作:
def getJsonNullKeys(json: Json): List[String] = {
json.asObject match {
case Some(jsonObject) => jsonObject.filter(j => j._2.isNull).keys.toList
case None => List[String]()
}
}
if (update.isRight) {
update.right.map(_(existingPerson)) match {
case Right(updatedPerson) =>
getNullKeys(incompletePersonJson).foreach { key =>
val field = existingPerson.getClass.getDeclaredField(key)
field.setAccessible(true)
field.set(updatedUpdate, None)
}
println(updatedUpdate)
// outputs Person(mr updated,42,None)
case Left(error) => println(error.toString)
}
}
希望 Circe 添加对此的支持,以便删除所有这些样板文件。