问题 PlayFramework:如何在没有将可选字段设置为null的情况下生成JSON


以下是创建帐户的课程:

class Account private(private var json: JsValue) {

  private def setValue(key: JsPath, value: JsValue) = {
    value match {
      case JsNull => json.transform(key.json.prune).map(t => json = t)
      case _ => json.transform((__.json.update(key.json.put(value)))).map(t => json = t)
    }
 }

  def asJson = json

  def id_= (v: Option[String]) = setValue((__ \ 'id), Json.toJson(v))
  def id = json as (__ \ 'id).readNullable[String]
  def name = json as (__ \ 'name).read[String]
  def name_= (v: String) = setValue((__ \ 'name), Json.toJson(v))
  def ownerId = json as (__ \ 'ownerId).read[String]
  def ownerId_= (v: String) = setValue((__ \ 'ownerId), Json.toJson(v))
  def openingTime = json as (__ \ 'openingTime).read[LocalDateTime]
  def openingTime_= (v: LocalDateTime) = setValue((__ \ 'openingTime), Json.toJson(v))
  def closingTime = json as (__ \ 'closingTime).readNullable[LocalDateTime]
  def closingTime_= (v: Option[LocalDateTime]) = setValue((__ \ 'closingTime),    Json.toJson(v))

  def copy(json: JsValue) = Account(this.json.as[JsObject] ++ json.as[JsObject]).get
}

object Account {

  val emptyObj = __.json.put(Json.obj())

  def apply(json: JsValue): JsResult[Account] = {
    validateAccount.reads(json).fold(
      valid = { validated => JsSuccess(new Account(validated)) },
      invalid = { errors => JsError(errors) }
    )
  }

  def apply(
    id: Option[String],
    name: String,
    ownerId: String,
    openingTime: LocalDateTime,
    closingTime: Option[LocalDateTime]
  ): JsResult[Account] = apply(Json.obj(
    "id" -> id,
    "name" -> name,
    "ownerId" -> ownerId,
    "openingTime" -> openingTime,
    "closingTime" -> closingTime
  ))

  def unapply(account: Account) = {
    if (account eq null) None
    else Some((
      account.id,
      account.name,
      account.ownerId,
      account.openingTime,
      account.closingTime
    ))
  }

  implicit val accountFormat = new Format[Account] {
    def reads(json: JsValue) = Account(json)
    def writes(account: Account) = account.json
  }

  /**
    * Validates the JSON representation of an [[Account]].
    */
  private[auth] val validateAccount = (
    ((__ \ 'id).json.pickBranch or emptyObj) ~
    ((__ \ 'name).json.pickBranch) ~
    ((__ \ 'ownerId).json.pickBranch) ~
    ((__ \ 'openingTime).json.pickBranch) ~
    ((__ \ 'closingTime).json.pickBranch or emptyObj)
  ).reduce
}

如您所见,有些字段是可选的,如 id 和 closingTime。如果是可选字段 Noneapply 上面的方法产生以下JSON:

{
  "id" : null,
  "name" : "Default",
  "ownerId" : "52dfc13ec20900c2093155cf",
  "openingTime" : "2014-02-02T19:22:54.708",
  "closingTime" : null
}

即使这可能是正确的,它也不是我想要的。例如,如果可选字段是 None,我需要获得以下JSON:

{
  "name" : "Default",
  "ownerId" : "52dfc13ec20900c2093155cf",
  "openingTime" : "2014-02-02T19:22:54.708",
}

话虽如此,我该如何预防 apply 从生成 null 字段?我要换掉 Json.obj(...) 有这样的东西?

JsObject(
  Seq() ++ (if (id.isDefined) Seq("id" -> JsString(id.get)) else Seq()
  ) ++ Seq(
    "name" -> JsString(name),
    "ownerId" -> JsString(ownerId),
    "openingTime" -> Json.toJson(openingTime)
  ) ++ (if (closingTime.isDefined) Seq("closingTime" -> Json.toJson(closingTime)) else Seq()
))

有没有更好的办法?


5729
2018-02-02 18:43


起源



答案:


Writes 由。。。生产 Json.writes 你会得不到 nullS:

case class Account(id: Option[String],
                   name: String,
                   ownerId: String,
                   openingTime: Int,
                   closingTime: Option[Int])

// in general you should add this to companion object Account
implicit val accountWrites = Json.writes[Account]

val acc = Account(None, "Default", "52dfc13ec20900c2093155cf", 666, None)

Json prettyPrint Json.toJson(acc)
// String = 
// {
//   "name" : "Default",
//   "ownerId" : "52dfc13ec20900c2093155cf",
//   "openingTime" : 666
// }

你可以实施 Writes[(Option[String], String, String, Int, Option[Int])] 如果您不想使用自定义类,请自己动手 Account 喜欢这个:

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

val customWrites = (
  (JsPath \ "id").writeNullable[String] ~
  (JsPath \ "name").write[String] ~
  (JsPath \ "ownerId").write[String] ~
  (JsPath \ "openingTime").write[Int] ~
  (JsPath \ "closingTime").writeNullable[Int]
).tupled

customWrites writes (None, "Default", "52dfc13ec20900c2093155cf", 666, None)
// JsObject = {"name":"Default","ownerId":"52dfc13ec20900c2093155cf","openingTime":666}

12
2018-02-02 19:03



我已将完整代码添加到我的帖子中...请参阅随播对象中的validateAccount ...我使用此验证程序验证其中一个两个应用方法中的输入JSON。 - j3d
@ j3d:是的,看起来问题就在这里`或emptyObj. I guess as a workaround you could just replace valid = {validated => JsSuccess(new Account(validated))},`with valid = { _ => JsSuccess(new Account(json)) }, - senia
@ j3d:你也可以尝试隐含地添加`〜> [Reads [JsValue]]` ).reduce: ).reduce ~> implicitly[Reads[JsValue]] - senia
@ j3d为什么你不会只创建一个case类(比如在我的回答中)+伴随对象 implicit val accountFormat = Json.format[Account]? - senia
以上建议均无效。让我为您提供更多信息:我的实体类具有内部JSON表示......它们可以用作JSON或类似POJO的对象。传入数据始终是JSON(这是一个REST API),需要进行验证和转换。然后,我将这些实体类保存在数据库中,该数据库可以是MongoDB或任何SQL数据库。当我保存到MongoDB时,我使用JSON表示,而当我保存到SQL数据库时,我使用props映射字段。 - j3d


答案:


Writes 由。。。生产 Json.writes 你会得不到 nullS:

case class Account(id: Option[String],
                   name: String,
                   ownerId: String,
                   openingTime: Int,
                   closingTime: Option[Int])

// in general you should add this to companion object Account
implicit val accountWrites = Json.writes[Account]

val acc = Account(None, "Default", "52dfc13ec20900c2093155cf", 666, None)

Json prettyPrint Json.toJson(acc)
// String = 
// {
//   "name" : "Default",
//   "ownerId" : "52dfc13ec20900c2093155cf",
//   "openingTime" : 666
// }

你可以实施 Writes[(Option[String], String, String, Int, Option[Int])] 如果您不想使用自定义类,请自己动手 Account 喜欢这个:

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

val customWrites = (
  (JsPath \ "id").writeNullable[String] ~
  (JsPath \ "name").write[String] ~
  (JsPath \ "ownerId").write[String] ~
  (JsPath \ "openingTime").write[Int] ~
  (JsPath \ "closingTime").writeNullable[Int]
).tupled

customWrites writes (None, "Default", "52dfc13ec20900c2093155cf", 666, None)
// JsObject = {"name":"Default","ownerId":"52dfc13ec20900c2093155cf","openingTime":666}

12
2018-02-02 19:03



我已将完整代码添加到我的帖子中...请参阅随播对象中的validateAccount ...我使用此验证程序验证其中一个两个应用方法中的输入JSON。 - j3d
@ j3d:是的,看起来问题就在这里`或emptyObj. I guess as a workaround you could just replace valid = {validated => JsSuccess(new Account(validated))},`with valid = { _ => JsSuccess(new Account(json)) }, - senia
@ j3d:你也可以尝试隐含地添加`〜> [Reads [JsValue]]` ).reduce: ).reduce ~> implicitly[Reads[JsValue]] - senia
@ j3d为什么你不会只创建一个case类(比如在我的回答中)+伴随对象 implicit val accountFormat = Json.format[Account]? - senia
以上建议均无效。让我为您提供更多信息:我的实体类具有内部JSON表示......它们可以用作JSON或类似POJO的对象。传入数据始终是JSON(这是一个REST API),需要进行验证和转换。然后,我将这些实体类保存在数据库中,该数据库可以是MongoDB或任何SQL数据库。当我保存到MongoDB时,我使用JSON表示,而当我保存到SQL数据库时,我使用props映射字段。 - j3d