我想以递归方式将一个类写入Json,所以我使用以下隐式写入:
implicit val writesObject : Writes[Object] = (
(__ \ "id").writeNullable[String] ~
(__ \ "list").lazyWriteNullable(Writes.traversableWrites[Object](writesObject))
)(unlift(Object.unapply)
其中Object是这样的类:
case class Object(id: Option[String], list: Option[Seq[Object]])
它有效,但是如果“list”为空,我想阻止它打印任何内容。例如:
我想:
{ id: "someID",
list: [
{
id: "someOtherId"
}
]
}
我目前得到(但不想要):
{ id: "someID",
list: [
{
id: "someOtherId"
list: []
}
]
}
我怎样才能做到这一点?我是Play / Scala的新手,不确定我应该注意什么,所以任何指针都会有所帮助。我正在使用Scala 2.2.1。
PS:我已经检查了Scala Json Combinators,但没有看到任何关于如何完成此操作的参考。
更新
所以我的问题不是该列表为空,但该列表为空。这就是lazyWriteNullable无效的原因。
测试johanandren的答案我想出了以下JsPath扩展,返回Option [T]并支持递归写入的惰性格式:
def lazyWriteNullableIterable[T <: Iterable[_]](w: => Writes[T]): OWrites[Option[T]] = OWrites((t: Option[T]) => {
if(t != null) {
t.getOrElse(Seq.empty).size match {
case 0 => Json.obj()
case _ => Writes.nullable[T](path)(w).writes(t)
}
}
else {
Json.obj()
}
})
由于
答案 0 :(得分:6)
您可以创建一个可以执行此操作的自定义OFormat。通过使用它隐式装饰JsPath,您可以将它包含在json组合器定义中:
implicit class PathAdditions(path: JsPath) {
def readNullableIterable[A <: Iterable[_]](implicit reads: Reads[A]): Reads[A] =
Reads((json: JsValue) => path.applyTillLast(json).fold(
error => error,
result => result.fold(
invalid = (_) => reads.reads(JsArray()),
valid = {
case JsNull => reads.reads(JsArray())
case js => reads.reads(js).repath(path)
})
))
def writeNullableIterable[A <: Iterable[_]](implicit writes: Writes[A]): OWrites[A] =
OWrites[A]{ (a: A) =>
if (a.isEmpty) Json.obj()
else JsPath.createObj(path -> writes.writes(a))
}
/** When writing it ignores the property when the collection is empty,
* when reading undefined and empty jsarray becomes an empty collection */
def formatNullableIterable[A <: Iterable[_]](implicit format: Format[A]): OFormat[A] =
OFormat[A](r = readNullableIterable(format), w = writeNullableIterable(format))
}
这将允许您使用json组合器语法创建格式/读/写,如下所示:
case class Something(as: List[String], v: String)
import somewhere.PathAdditions
val reads: Reads[Something] = (
(__ \ "possiblyMissing").readNullableIterable[List[String]] and
(__ \ "somethingElse").read[String]
)(Something)
val writes: Writes[Something] = (
(__ \ "possiblyMissing").writeNullableIterable[List[String]] and
(__ \ "somethingElse").write[String]
)(unlift(Something.unapply))
val format: Format[Something] = (
(__ \ "possiblyMissing").formatNullableIterable[List[String]] and
(__ \ "somethingElse").format[String]
)(Something, unlift(Something.unapply))