简体   繁体   English

在案例类中使用json4s序列化None

[英]Serializing Nones with json4s in a case class

I can't figure this out, Say I have a case class with Options in it like: 我无法弄清楚,说我有一个带有Option的案例类,例如:

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

If I attempt to serialize it to json using json4s as proscribed by the Scalaltra guides, any Nones in my case class get removed from the output. 如果我按照Scalaltra指南的规定,尝试使用json4s将其序列化为json,则我的case类中的所有None都将从输出中删除。 Such that the following code 这样下面的代码

  protected implicit val jsonFormats: Formats = DefaultFormats

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

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

will produce an output of "{"id":1}", I'd like to have an output like: {"id":1, "noteA": null, "noteB": null} 将会产生“ {{id”:1}”的输出,我想有一个输出:{“ id”:1,“ noteA”:null,“ noteB”:null}

I've written a CustomSerializer along the lines of: 我已经按照以下方式编写了一个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) }))

Which does the same thing as the default formatter. 与默认格式化程序的功能相同。

I would think that changing the last line to this would work 我认为将最后一行更改为这样可以工作

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

but does not compile. 但不会编译。

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

I'm wondering how I might do match for a Some/None in the noteA and noteB fields and return a JNull in the case of a None for either of those members. 我想知道如何在noteA和noteB字段中匹配Some / None,并在其中一个成员都为None的情况下返回JNull。

Thanks 谢谢

got it: 得到它了:

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

patience is a virtue, just not one of mine. 忍耐是一种美德,不是我的一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM