3
votes

Any way to serialize a Scala case class to JSON and have the ability to provide custom serialized names ?

For example, In Java this can be done using the Gson library :

 public class SomeClassWithFields {
   @SerializedName("name") private final String someField;
   private final String someOtherField;

   public SomeClassWithFields(String a, String b) {
     this.someField = a;
     this.someOtherField = b;
   }
 }

I tried doing this in Scala :

case class SomeClassWithFields(@SerializedName("name") someField:String)

but it seems to have no effect .

Any thoughts ?

3

3 Answers

4
votes

Yes it can be done. Here's how:

case class SomeClassWithFields(@(SerializedName @scala.annotation.meta.field)("name") someField:String)

The syntax is strange (note that the outer '@' wraps the "SerializedName" and the scala field annotation) but it works fine. See more details at: https://issues.scala-lang.org/plugins/servlet/mobile#issue/SI-8975

2
votes

Further improving Corindiano's answer by making it into a custom annotation, which can be (re)used elsewhere.

import scala.annotation.meta.field

case class SomeClassWithFields(@SerializedNameField(value = "name") someField:String) { ... }
object SomeClassWithFields {
    type SerializedNameField = com.google.gson.annotations.SerializedName @field
}
-1
votes

You can do it with spray-json calling the jsonFormat overloads.

Here's how it would work with your example:

import spray.json._

case class SomeClassWithFields( someField:String)

object SomeClassJsonProtocol extends DefaultJsonProtocol {
  implicit val someClassFormat = jsonFormat(SomeClassWithFields,"name")
}