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

I am creating JSON with Play 2.4.3 and Scala as follows, providing an implicit Writes[DeviceJson] created using 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 does not compile, since I am trying to use the reserved word type as the name of a field in the case class.

In this scenario, what is the easiest way to output JSON field names, such as type or match , that I cannot use as Scala field names?

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

I know I can do this by copying my own implementation of Writes :

 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 many fields. Is there an easier way?

+4
json scala playframework
Dec 01 '15 at 10:08
source share
1 answer

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

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

In this case, your Writes should work

+11
Dec 01 '15 at 11:05
source share



All Articles