Spring template engine for rendering JSON
Asked Answered
F

1

3

I come from Ruby and have just started testing Spring and find it fairly nice.

However i'm used to being able to customize the rendered JSON output with libraries like rabl and it feels really wrong to expose internal models straight out into the JSON as i do now with the annotation @ResponseBody and just returning the model.

Does anyone have any tips on libraries similar to rabl but for java/spring or is there an existing way to do it easily with spring without manually writing templates in JSON?

Frydman answered 11/7, 2013 at 10:57 Comment(0)
T
2

Spring uses Jackson to do the JSON (de-)serialisation. Take a look at the Jackson wiki; it describes several ways to customise the way JSON is generated or interpreted.

As I understand from your comment, you have a couple of customisations in mind.

  • Renaming fields can be achieved by annotating the field with @JsonProperty("name")
  • Not rendering fields can be achieved by annotating the field with @JsonIgnore

But these do require you to touch your model. As far as I know, there is no way you could achieve that without at least changing your model classes slightly. There's the concept of "views" in Jackson but they still require putting annotations on your model. In practice, I've never experienced problems with Java classes being annotated with both JPA and Jackson annotations, by the way.

Finally, you can consider creating two versions of your model - one that comes from your database (or whatever source of data you have), and one that is used to interact with the user interface. However, that would require a layover of transformers or converters. Whether or not that is an option is up to you.

Trotline answered 11/7, 2013 at 11:6 Comment(1)
Yes, i looked around and found out about that too but as far as i understand that only allows me to do global things like replacing null with an empty string or the other way around. What i'm looking for is a way to define views that convert a model into JSON and allows me to do some transformations like rabl does (like only rendering certain fields and renaming fields and pulling in related objects). I know there are annotations that you can put on the models to affect the jackson output but i'd like to do that on a view to view basis and i don't want to touch my models for this.Frydman

© 2022 - 2024 — McMap. All rights reserved.