rest - 如何在Grails 2.3中的JSON呈现中排除集合的属性

标签 rest grails

我正在尝试设置其余的Web服务(JSON),这就是我得到的:

{"name":"test","routines":[{"class":"Routine","id":1},{"class":"Routine","id":2}]}

这就是我想要得到的:
{"name":"test","routines":[{"name": "routine-1"},{"name": "routine-2"}]}

我有这些域:
class Program {

    String name;

    static hasMany = [routines: Routine]
}
class Routine {

    String name

}

我有这个 Controller :
class ProgramController extends RestfulController {

    static responseFormats = ['json']

    def show(Program program) {
        respond program
    }
}

我在resources.groovy中添加了它
programRenderer(JsonRenderer, Program) {
    excludes = ['class', 'id']
}

routineRenderer(JsonRenderer, Routine) {
    excludes = ['class', 'id']
 }

如何使用ProgramController的show方法/操作将routine的name属性包含在json响应中?

最佳答案

ObjectMarshaller方法是技术上正确的方法。但是,代码编写起来很麻烦,并且将域的字段与编码器同步非常麻烦。

本着Groovy的精神,让事情变得非常简单,我们很高兴为每个REST域添加了一个out()方法。

Program.groovy

class Program {

   String name
   static hasMany = [routines: Routine]

   def out() {
      return [
         name:     name,
         count:    routines?.size(),
         routines: routines?.collect { [name: it.name] }
         ]
      }

}

ProgramController.groovy
import grails.converters.JSON

class ProgramController {

   def show() {
      def resource = Program.read(params.id)
      render resource.out() as JSON
      }

}

JSON响应
{
   name:     "test",
   count:    2,
   routines: [{ name: "routine-1" }, { name: "routine-2" }]
}
out()方法可轻松自定义响应JSON,例如为例程数添加count

关于rest - 如何在Grails 2.3中的JSON呈现中排除集合的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22970254/

相关文章:

java - 如何尝试从 java 客户端使用 Sharepoint 的 Rest api 但收到状态代码 403 Forbidden

grails - 如何更改 f :field (textField) by a textArea using Grails Fields Plugin

unit-testing - 如何对使用springSecurityService的 Controller 进行单元测试?

java - Grails 应用程序 - 将非 www 版本重定向到网站的 www 版本

java - 对于@GET操作,使用@QueryParam或@FormParam

java - 文件上传时出现 angularJS 405 错误

javascript - JS : How to change the value of an object's property according to that object attribute

asp.net - Swagger 忽略 xml 参数标签

grails - Grails插件的依赖

Grails - 进行 Controller 测试时如何在 Controller 中实例化服务