3

继续这个问题,我有以下代码,但想将nullJSON 值映射到 Scala None。我得到的当前行为是包含与不包含它之间没有key区别null ("key": null)。我想将此映射到None以便我可以将数据库条目设置为null. 此外,当 akey不包含在 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))
4

1 回答 1

0

I ended up with the following solution, it might be not ideal and it's not using Circe but it does the job for me:

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

Hope Circe adds support for this so all this boilerplate can be removed.

于 2018-04-05T19:17:46.243 回答