【问题标题】:Serializing Nones with json4s in a case class在案例类中使用 json4s 序列化 None
【发布时间】:2014-08-28 20:52:28
【问题描述】:

我想不通,假设我有一个带有选项的案例类,例如:

  case class Note(id: Int, noteA: Option[String], noteB: Option[String])

如果我尝试使用 Scalaltra 指南所禁止的 json4s 将其序列化为 json,则我的案例类中的任何 None 都会从输出中删除。这样下面的代码

  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  get("/MapWNone") {
    new Note(1, None, None)
  }

会产生“{”id”:1}”的输出,我想要一个类似的输出:{“id”:1, “noteA”: null, “noteB”: null}

我编写了一个 CustomSerializer,如下所示:

class NoteSerializer extends CustomSerializer[Note](format => ({
     |   case jv: JValue =>
     |     val id = (jv \ "id").extract[Int]
     |     val noteA = (jv \ "noteA").extract[Option[String]]
     |     val noteB = (jv \ "noteB").extract[Option[String]]
     |     Note(id, noteA, noteB)
     | }, { case n: Note => ("id" -> n.id) ~ ("noteA" -> n.noteA) ~ ("noteB" -> n.noteB) }))

与默认格式化程序的作用相同。

我认为将最后一行更改为这样会起作用

case n: Note => ("id" -> n.id) ~ ("noteA" -> n.noteA.getOrElse(JNull)) ~ ("noteB" -> n.noteB.getOrElse(JNull))

但不编译。

No implicit view available from java.io.Serializable => org.json4s.JsonAST.JValue

我想知道如何匹配 noteA 和 noteB 字段中的 Some/None 并在其中任何一个成员为 None 的情况下返回 JNull。

谢谢

【问题讨论】:

    标签: scala scalatra json4s


    【解决方案1】:

    知道了:

    case n: Note => ("id" -> n.id) ~ ("noteA" -> n.noteA.getOrElse(null)) ~ ("noteB" -> n.noteB.getOrElse(null)) }))
    

    耐心是一种美德,但不是我的。

    【讨论】:

      最近更新 更多