JSON 隐式 Reads/Writes 在 Playframerowk 中有一个元素不工作

JSON implicit Reads/Writes in Playframerowk with one element not working

说我必须class知道我将使用它进行读写JSON

case class OrganizationData(var kind: Option[String],var id: Option[String],var organizationReference: OrganizationReferenceData,var objectHash: Option[String],var friendlyName: Option[String])



case class OrganizationReferenceData(var organizationId:String)

以下为读写

implicit val organizationWrites = (
(__ \ "kind").writeNullable[String] and
  (__ \ "id").writeNullable[String] and
  (__ \ "organizationReference").write[OrganizationReferenceData] and
  (__ \ "objectHash").writeNullable[String] and
  (__ \ "friendlyName").writeNullable[String]
) ( unlift( OrganizationData.unapply ) )

  implicit val OrganizationReferenceDataWrites:Writes[OrganizationReferenceData] = (
(__ \ "organizationId").write[String]
) ( unlift( OrganizationReferenceData.unapply ) )

当我尝试编译时出现以下错误。

Error:(54, 34) overloaded method value write with alternatives:
(t: String)(implicit w:   play.api.libs.json.Writes[String])play.api.libs.json.OWrites[play.api.libs.json.JsValue] <and>
(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OWrites[String]
cannot be applied to (config.core.OrganizationReferenceData => String)
(__ \ "organizationId").write[String]
                             ^

我是不是漏掉了什么?我看到的一件奇怪的事情是,如果我在 "OrganizationReferenceDataWrites" class 中添加另一个字段并让它编译写入元素。那么,如果我们不能拥有单个元素,那么最佳做法是什么?

我不确定您为什么会收到该消息,但另一种方法可能是:

implicit val OrganizationReferenceDataWrites = new Writes[OrganizationReferenceData] {
  def writes(organizationReferenceData: OrganizationReferenceData) = Json.obj(
    "organizationId" -> organizationReferenceData.organizationId)
}

警告:我对我的 combinators 了解不够,无法知道这是否 完全 等价。

顺便说一句,您是否出于某种原因使用可变 (var) 变量?