Reputation: 875
I can't figure this out, Say I have a case class with Options in it like:
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. 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}
I've written a CustomSerializer along the lines of:
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.
Thanks
Upvotes: 2
Views: 1115
Reputation: 875
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.
Upvotes: 0