json - PlayFramework:如何在不将可选字段设置为 null 的情况下生成 JSON

标签 json scala playframework

下面是一个用于创建帐户的类:

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()
))

有没有更好的办法?

最佳答案

Writes制作人 Json.writes你不会得到null s:

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}

关于json - PlayFramework:如何在不将可选字段设置为 null 的情况下生成 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514634/

相关文章:

javascript - 添加监听器以向文本字段创建警告消息

playframework - 使用 Slick 3.0 在同一事务中进行多次插入

scala - 如何使用 Spark/Scala 中的频率计数从文本文件创建二元组?

javascript - 无法从服务器上的 PHP 文件获取 JSON 数据

javascript - 如何使用 Angular JavaScript 从(php 编码的 json)获取值?

json - RESTify on Node.js POST body/json

Scala:如何定义输入为 (f, args) 且输出为 f(args) 的函数?

scala - Janusgraph - 检查和获取两个顶点之间的边缘的有效方法

javascript - 在本地主机上发推文和关注 (Twitter)

javascript - 解析 JSON 时出现问题