【问题标题】:PlayFramework: How to generate JSON without optional fields set to nullPlayFramework:如何在不将可选字段设置为 null 的情况下生成 JSON
【发布时间】:2014-02-02 18:43:37
【问题描述】:

下面是一个创建账户的类:

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
}

如您所见,有些字段是可选的,例如 idclosingTime。如果可选字段为None,则上面的apply 方法会生成以下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()
))

有没有更好的办法?

【问题讨论】:

    标签: json scala playframework


    【解决方案1】:

    使用由Json.writes 制作的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
    // }
    

    如果您不想像这样使用自定义类Account,您可以自己实现Writes[(Option[String], String, String, Int, Option[Int])]

    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}
    

    【讨论】:

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