光滑的结果给了json

时间:2016-10-18 21:38:59

标签: json scala playframework

我想要做的是受此启发:https://www.playframework.com/documentation/2.5.x/ScalaJsonHttp

我希望Person可以加Address。在我的例子中,它实际上有很多,所以一个人可以拥有多个地址,并且一个地址可以附加到多个人身上。

查询不是问题。我从DB层返回Future[Seq[((Person, PersonAddress), Address)]]

当我想将结果作为json返回时,我的问题就开始了。对于单独的Person,这很简单,因为案例类已经很小心了,但对于这样的Seq来说它更复杂。

所以我尝试了这个:

1)DB现在只返回Future[Seq[((Person, PersonAddress)]],让我更容易理解

2)case class PersonWithPersonAddress(person: Person, personAddress: PersonAddress)被添加为帮助者,而不是使用Tuple2[Person, PersonAddress]

3)我写了以下作者:

 implicit val writes: Writes[PersonWithPersonAddress] = (
      (JsPath \ "person").write[Person],
      (JsPath \ "personAddress").write[PersonAddress]
    ) (unlift(PersonWithPersonAddress.unapply))

根据编译器,这还不够。

  

找不到类型PersonAddress的Json序列化程序。尝试为此类型实现隐式写入或格式。

然后我尝试添加: implicit val personFormat = Json.format[Person] implicit val PersonAddressFormat = Json.format[PersonAddress]

但我得到了

(play.api.libs.json.OWrites[Person], play.api.libs.json.OWrites[PersonAddress]) does not take parameters

我继续手动编写Writes[Person],但这当然不会改变为Json.format[Person]

现在我没有想法

1 个答案:

答案 0 :(得分:1)

这对你来说应该足够了:

import play.api.libs.json.Json

implicit val personFormat = Json.format[Person]
implicit val personAddressFormat = Json.format[PersonAddress]
implicit val personWithPersonAddressFormat = Json.format[PersonWithPersonAddress]

如果您仍想逐个字段定义Writes,请尝试以下操作:

import play.api.libs.functional.syntax._
import play.api.libs.json._

implicit val personWrites = Json.writes[Person]
implicit val personAddressWrites = Json.writes[PersonAddress]
implicit val personWithAddressWrites: Writes[PersonWithPersonAddress] = (
  (__ \ "person").write[Person] and
  (__ \ "personAddress").write[PersonAddress]
)(unlift(PersonWithPersonAddress.unapply))