我正在尝试设置其余的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/

10-11 22:28
查看更多