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?
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 ofjsonFormat3(Person)
).
jrudolph, if you change your comment to an answer, I'll delete this.
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