我尝试使用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"
]
}
怎么做?
答案 0 :(得分:3)
已解决,关键是定义自定义EncodeJson规则并使用->?:
和field.map
:
implicit def PersonCodecJson: EncodeJson[Person] = EncodeJson((p: Person) =>
p.name.map("name" := _) ->?: ("age" := p.age) ->: ("things" := p.things) ->: jEmptyObject)