Setting JSON object property names using Spray JSON

I use spray-json to serialize an object tree based on a class hierarchy, for example:

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, of course, is a contrived example; the real code base contains many classes and fields. However, the idea is that there is a trait that contains some common meanings. Now the question is, is there a way to format JSON so that instead of _id the property name is just id .

Now before you go over and say the JsonFormat extension, the question arises as to whether I can only implement this once for all classes extending Base , without applying a format for each of the classes. As I mentioned, there are many classes, and implementing custom formats for each of them will be quite tedious, and I assume that this will require quite a lot of maintenance. It would be nice if I could annotate _id val in Base , for example. Is there something that can be done to avoid implementing formats for each of the classes?

+5
source share
1 answer

Here is jrudolph's comment as an answer so people can see easily. Perfect solution!

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

jrudolph, if you change your comment to an answer, I will delete it.

+6
source

Source: https://habr.com/ru/post/1207335/


All Articles