4

我正在尝试使用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"
  ]
}

怎么做?

4

1 回答 1

3

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

implicit def PersonCodecJson: EncodeJson[Person] = EncodeJson((p: Person) =>
  p.name.map("name" := _) ->?: ("age" := p.age) ->: ("things" := p.things) ->: jEmptyObject)
于 2014-05-28T07:34:08.053 回答