假设我必须使用它来读取和写入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”类中添加另一个字段并且编译它的write元素。那么,如果我们不能有一个单一元素,那么最佳做法是什么呢?
答案 0 :(得分:1)
我不确定你为什么要收到这条消息,但另一种方法可能是:
implicit val OrganizationReferenceDataWrites = new Writes[OrganizationReferenceData] {
def writes(organizationReferenceData: OrganizationReferenceData) = Json.obj(
"organizationId" -> organizationReferenceData.organizationId)
}
警告:我不知道我的combinators是否足以知道这是完全等效。
BTW您是否因为某种原因使用了可变( var )变量?