如果值为None,如何在生成json字符串时忽略项?

时间:2014-05-28 06:15:26

标签: json scala optional argonaut

我尝试使用Argonaut从Scala实例生成JSON字符串。

import argonaut._, Argonaut._

case class Person(name: Option[String], age: Int, things: List[String])

implicit def PersonCodecJson =
  casecodec3(Person.apply, Person.unapply)("name", "age", "things")

val person = Person(Some("Freewind"), 2, List("club"))

val json: Json = person.asJson

val prettyprinted: String = json.spaces2

它将生成:

{
  "name" : "Freewind",
  "age" : 2,
  "things" : [
    "club"
  ]
}

当名称为None时:

val person = Person(None, 2, List("club"))

它将生成:

{
  "name" : null,
  "age" : 2,
  "things" : [
    "club"
  ]
}

但实际上我希望它是:

{
  "age" : 2,
  "things" : [
    "club"
  ]
}

怎么做?

1 个答案:

答案 0 :(得分:3)

已解决,关键是定义自定义EncodeJson规则并使用->?:field.map

implicit def PersonCodecJson: EncodeJson[Person] = EncodeJson((p: Person) =>
  p.name.map("name" := _) ->?: ("age" := p.age) ->: ("things" := p.things) ->: jEmptyObject)