Scala reserved word as JSON field name with Json.writes[A] (Play equivalent for @SerializedName)

本秂侑毒 提交于 2019-12-23 09:48:31

问题


I'm producing JSON with Play 2.4.3 & Scala in the following fashion, providing an implicit Writes[DeviceJson] created with Json.writes.

import play.api.libs.json.Json

case class DeviceJson(name: String, serial: Long, type: String)

object DeviceJson {
  implicit val writes = Json.writes[DeviceJson]
}

Of course, the above doesn't compile as I'm trying ot use the reserved word type as field name in the case class.

In this scenario, what is the simplest way to output JSON field names such as type or match that I can't use as Scala field names?

With Java and Gson, for example, using a custom JSON field name (different from the field name in code) would be trivial with @SerializedName annotation. Similarly in Jackson with @JsonProperty.

I know I can do this by rolling my own Writes implementation:

case class DeviceJson(name: String, serial: Long, deviceType: String)

object DeviceJson {
  implicit val writes = new Writes[DeviceJson] {
    def writes(json: DeviceJson) = {
      Json.obj(
        "name" -> json.name,
        "serial" -> json.serial,
        "type" -> json.deviceType
      )
    }
  }
}

But this is clumsy and repetitive, especially if the class has a lot of fields. Is there a simpler way?


回答1:


In your case class, you can use backtick for field name:

case class DeviceJson(name: String, serial: Long, `type`: String)

With this, your Writes should work



来源:https://stackoverflow.com/questions/34017680/scala-reserved-word-as-json-field-name-with-json-writesa-play-equivalent-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!