【问题标题】:Map null values to None in Scala using Circe使用 Circe 将空值映射到 Scala 中的 None
【发布时间】:2023-03-03 00:31:01
【问题描述】:

继续question,我有以下代码,但想将null JSON 值映射到 Scala None。我得到的当前行为是包含keynull ("key": null) 和不包含它之间没有区别。我想将其映射到None,这样我就可以将数据库条目设置为null。此外,当 JSON 中不包含 key 时,将其映射到现有值。

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))

【问题讨论】:

    标签: json scala dictionary null circe


    【解决方案1】:

    我最终得到了以下解决方案,它可能并不理想,它没有使用 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 增加对此的支持,以便可以删除所有这些样板。

    【讨论】:

      猜你喜欢
      • 2017-07-10
      • 2021-06-05
      • 2021-06-27
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 2011-01-12
      相关资源
      最近更新 更多