用于渲染JSON的Spring模板引擎 [英] Spring template engine for rendering JSON

查看:794
本文介绍了用于渲染JSON的Spring模板引擎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Ruby,刚刚开始测试Spring,发现它还不错.

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

但是我习惯使用 rabl 之类的库来自定义呈现的JSON输出并且像我现在使用注释@ResponseBody一样直接将内部模型直接公开到JSON并只返回模型,确实是错误的.

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.

除了java/spring之外,还有人对类似于rabl的库有任何提示吗?还是有一种现有的方法可以轻松地使用spring进行操作,而无需在JSON中手动编写模板?

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?

推荐答案

Spring使用Jackson进行JSON(反)序列化.看一看 Jackson Wiki ;它描述了几种自定义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
  • 注释字段来实现
  • Renaming fields can be achieved by annotating the field with @JsonProperty("name")
  • Not rendering fields can be achieved by annotating the field with @JsonIgnore

但是这些确实需要您触摸模型.据我所知,如果不至少稍稍更改模型类,就不可能实现这一目标. Jackson中有"视图"的概念,但它们仍然需要在模型上添加注释.在实践中,顺便说一下,我从来没有遇到过用JPA和Jackson注释对Java类进行注释的问题.

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.

这篇关于用于渲染JSON的Spring模板引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆