Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing JSON object property names with Spray JSON

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?

like image 828
yby Avatar asked Nov 20 '14 20:11

yby


1 Answers

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.

like image 115
Jon Onstott Avatar answered Oct 16 '22 10:10

Jon Onstott