在gson中渲染少量模型

n3schb8v  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(130)

是否可以将少量对象发送到gson渲染视图中?我尝试在controller中使用:

respond trainings, [status: OK, view:"trainingsByClients", model: [myVariable: "test", anotherVariable: 123]]

gson视图中:

model {
    Iterable<Training> trainingList
    String myVariable
}

json {
    myVariable myVariable
    trainings tmpl.training(trainingList ?: [])
}

并且它以如下方式响应:

{
  "myVariable": null,
  "trainings": [
    {
      "id": 3,
      "name": "test t",
      "numberOfAbsentClients": 0,
      "startDate": "2016-11-20T09:00:00+0000",
      "numberOfClients": 2,
      "section": {
    "id": 1,
    "name": "test sec"
      }
    },
    {
      "id": 10,
      "name": "test 2",
      "numberOfAbsentClients": 0,
      "startDate": "2016-11-09T11:00:00+0000",
      "numberOfClients": 2,
      "section": {
    "id": 2,
    "name": "sec 2"
      }
    }
  ]
}
oxalkeyp

oxalkeyp1#

好吧,我找到了解决办法:

render(view: "trainingsByClients", model: [trainingList: trainings, myVariable: "asdg"])

因此我们应该使用render而不是respond。响应没有正确地添加额外的模型对象。

ilmyapht

ilmyapht2#

实际上,在使用respond时,必须对所有模型属性使用g.render方法
示例GSON视图:

model {
    Iterable<Training> trainingList
    String myVariable
}

json {
    myVariable g.render(myVariable)
    trainings tmpl.training(trainingList ?: [])
}

这只与您在response.model参数中解析的模型相关

相关问题