7
votes

I'm using spray-json to serialize an object tree, which is based on a class hierarchy such as this:

trait Base {
  val _id: Long
}

case class Person(_id: Long, firstName: String, lastName: String) extends Base
case class Company(_id: Long, name: String) extends Base

This is of course a contrived example, the real codebase contains many classes and fields. The idea, however, is that there's a trait that contain some common values. Now the question is if there's a way I can format the JSON such that instead of _id the property name would be just id.

Now before you jump and tell to extend JsonFormat, the question is whether I can implement this just once for all classes that extend Base, without implementing a format for each of the classes. As I mentioned, there are many classes, and implementing custom formats for each would be quite tedious and I assume will require quite a lot of maintenance. It would be nice if I could annotate the _id val in Base for example. Is there anything that can be done to avoid implementing formats for each of the classes?

1
You can use jsonFormat(Person, "id", "firstName", "lastName") to set the names of the fields (instead of jsonFormat3(Person)).jrudolph
@jrudolph It's not ideal, because I still need to define it separately for each class. However, it's probably easiest way to go with spray-json. Could you please write it as an answer here so I could mark it as the best answer? Thanks!yby
Ah, another possibility that people have been using is overriding ProductFormat.extractFieldNames to provide a general mapping on the names.jrudolph

1 Answers

14
votes

Here is jrudolph's comment as an answer, to make it easy for people to see. Great solution!

You can use jsonFormat(Person, "id", "firstName", "lastName") to set the names of the fields (instead of jsonFormat3(Person)).

jrudolph, if you change your comment to an answer, I'll delete this.