views:

49

answers:

3

I have following mapping representing categories tree:

class Category {

  String name
  static belongsTo = [parent: Category]
  static hasMany = [categories: Category]

}

The thing I want to do is to render all of the category tree and exclude field parent from rendering.

render category as JSON 

renders only first level of hierarchy and doesn't render the names of child categories. I.e. having following tree:

Root->cat2->cat4 cat3

I have

{"class":"project.Category",
 "id":1,
 "categories":[{"class":"Category","id":2},
               {"class":"Category","id":3}],
 "name":"Root",
 "parent":null}

I don't want "class" and "parent" attributes and want to see cat4 data in this tree.

Is there some special lib or plugin or maybe it is possible to config standard JSON converter or domain class?

A: 

I think you'd have to do it yourself :-/

something like:

def categoryToMap( cat ) {
  def a = [ id:cat.id, name:cat.name ]
  if( cat.categories ) a << [ categories:cat.categories.collect { categoryToMap( it ) } ]
  a
}

then something like:

render categoryToMap( category ) as JSON
tim_yates
That will do but categories tree above is only simple exmapmle. But I am seek for more universal and if it possible standard way.
Vladimir
A: 

JSON-lib is a library that offers tight control over the format of Java/Groovy objects serialized to JSON. From the docs:

Since version 2.0 Json-lib has integrated Groovy support, meaning that POGOs can be transformed into JSON and back, in the same manner as you do now with POJOs.

Don
The question is actually: HOW to configure this lib?
Vladimir
A: 

You can try to build custom JSON via JSONBuilder:

render(builder:'json') {
  id(category.id)
name(category.name)
  categories {
    category.categories?.each {
      categories (
        id: it.id,
        name: it.name
      )
    }
  }
}
Olexandr