我来自 Ruby,刚刚开始测试 Spring,发现它相当不错。
但是,我习惯于使用rablJSON
之类的库来自定义渲染输出,并且像现在使用注释那样将内部模型直接暴露到模型中并只返回模型感觉真的很错误。JSON
@ResponseBody
有没有人对类似于 rabl 的库有任何提示,但是对于java/spring
或者是否有现有的方法可以使用 spring 轻松完成它而无需手动编写模板JSON
?
我来自 Ruby,刚刚开始测试 Spring,发现它相当不错。
但是,我习惯于使用rablJSON
之类的库来自定义渲染输出,并且像现在使用注释那样将内部模型直接暴露到模型中并只返回模型感觉真的很错误。JSON
@ResponseBody
有没有人对类似于 rabl 的库有任何提示,但是对于java/spring
或者是否有现有的方法可以使用 spring 轻松完成它而无需手动编写模板JSON
?
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.
@JsonProperty("name")
@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.