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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With