Scala保留字作为带有Json.writes [A]的JSON字段名称(与@SerializedName等效的播放方式) [英] Scala reserved word as JSON field name with Json.writes[A] (Play equivalent for @SerializedName)
问题描述
我正在使用Play 2.4.3&制作JSON. Scala以以下方式提供由Json.writes
创建的隐式Writes[DeviceJson]
.
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]
}
当然,以上内容无法编译,因为我试图在案例类中使用保留字type
作为字段名称.
Of course, the above doesn't compile as I'm trying ot use the reserved word type
as field name in the case class.
在这种情况下,最简单的输出JSON字段名称(例如不能用作Scala字段名称的type
或match
)的方法是什么?
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?
例如,对于Java和Gson,使用自定义JSON字段名称(与代码中的字段名称不同)对于
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
.
我知道我可以通过滚动自己的Writes
实现来做到这一点:
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?
推荐答案
在您的案例类中,可以将反引号用作字段名称:
In your case class, you can use backtick for field name:
case class DeviceJson(name: String, serial: Long, `type`: String)
有了这个,您的Writes
应该可以工作
With this, your Writes
should work
这篇关于Scala保留字作为带有Json.writes [A]的JSON字段名称(与@SerializedName等效的播放方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!