在 Grails 中将模型返回为 JSON 时如何处理延迟加载的引用
在 Grails 中,我有一个模型类 User,它与另一个模型类 Address 具有一对一的映射。当从我的控制器以 JSON 格式返回用户时,我从未看到地址类,只看到 id。在我的 User 类中,我有:
class User {
Address address
...
static mapping = {
...
address fetch: 'join'
...
}
然后在我的控制器中,我
User user = user.get(1)
render user as JSON
有 有没有办法更改映射以使“as JSON”拉回地址类?
我正在 Grails 1.3.7 上运行。
In Grails I have a model class User that has a one-to-one mapping with another model class Address. When returning a user in JSON format from my controller I never see the address class, just the id. In my User class I have:
class User {
Address address
...
static mapping = {
...
address fetch: 'join'
...
}
And then in my controller I do
User user = user.get(1)
render user as JSON
Is there a way to change the mapping to make the 'as JSON' pull back the address class?
I am running on Grails 1.3.7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种类型的 JSON 转换器,即:
.
.
你需要的是一个深度转换器,
只需将导入的类更改为:
注意: Grails 1.3.7 import grails.converters.deep.JSON 是可以的,在 Grails 2.0 中已弃用。
这两者之间的区别是,“深层”转换器还将对嵌套类进行 JSON 化,而标准转换器则不会。
希望有帮助
问候
Kushal
There are Two types of JSON Converters i.e:
.
.
What you need is a Deep Converter,
Just change the Imported Class To:
Note: Grails 1.3.7 import grails.converters.deep.JSON is fiine, in Grails 2.0 its deprecated.
The Difference Between these two is, that the "Deep" one will also JSONify the nested Classes, Whereas Standard Converter will not.
Hope that help
Regards
Kushal
您是否尝试过将转换器设置得更深?
JSON.use(“深”){
用户 user = user.get(1)
将用户渲染为 JSON
。
您可以在此处深入了解有关自定义对象编组器的一些内容,但我的第一个尝试是尝试深度转换
Have you tried setting your converter to be deep?
JSON.use("deep"){
User user = user.get(1)
render user as JSON
}
There is a bit of stuff around the Custom Object Marshallers that you can dig into here, but my first try would be to just try the deep conversion.