开发者

Grails JSON response of models and submodels (one to many)

I'm very new to Grails and so I hope I have an easy question for you.

I have a DomainModel and inside this model is a related Model (one-to-many). Let's say Service and a service as 'n' tasks. I select (via findAllBy()) e.g. 3 services and every service has at least one task or three for example.

Now my question. I don't want return "render foundServices as JSON". Reason: I don't want to let the people all over the world know my model definition and some maybe "secret" properties, which are all filled automatically by the database return/select. Is that a right thought, or is it a "too much and too deep security"-thought?

So I tried to find out how can I return relevant datas I need in a similiar way than these objects.

I tried:

List<Service> servicesSelection = Service.findAllByCompany("someCompany")
ArrayList services = new ArrayList();
for (Service service: servicesSelection) {
   ArrayList myService = new ArrayList()
   myService .add(service.id)
   myService .add(service.getServiceName())
   for (Tasks task: service.tasks) {
      ArrayList serviceTasks = new ArrayList()
      serviceTasks.add(task.id)
      serviceTasks.add(task.getTaskName())
      myService.add(serviceTasks)
   }
   services.add(myService)
}
render services as JSON

1) Is this too much "overhead"?

2) Do you think "ok doesn'n matter, return the whole DomainModel (from search result)"

3) If I put my own 'array lists" togethe开发者_JAVA技巧r, how can this be done to be similiar to domain-models to access easily all properties and the 'n' task-list in each service

Thank you very much!


It's not too much overhead if your security requirements dictate that certain information not be shared. In most cases, I don't think it's a problem to just convert the whole domain object to JSON, but your app might be a special case.

You could write the code to do this in a manner more consistent with Groovy/Grails practice:

def services = []
for (s in Service.findAllByCompany("someCompany")) {
   def tasks = []
   for (t in s.tasks) {
      tasks << [id: t.id, taskName: t.taskName]
   }
   def service = [id: s.id, serviceName: s.serviceName, tasks: tasks]
   services << service
}
render services as JSON

I just noticed that your code also didn't provide keys for the ids and names (using lists instead of maps), which is probably something you'd want to do and which the example code I've written does.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜