Customizing JSON object property names with Spray JSON
Asked Answered
A

1

9

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?

Apron answered 20/11, 2014 at 20:6 Comment(3)
You can use jsonFormat(Person, "id", "firstName", "lastName") to set the names of the fields (instead of jsonFormat3(Person)).Puente
@Puente 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!Apron
Ah, another possibility that people have been using is overriding ProductFormat.extractFieldNames to provide a general mapping on the names.Puente
D
17

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.

Devanagari answered 17/11, 2015 at 16:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.