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?

3 Answers 3

2

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
      )
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

The question is actually: HOW to configure this lib?
Put it on your classpath either by adding the JAR to the /lib directory of your Grails app, or specifying it as a dependency in BuildConfig.groovy
0

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

1 Comment

That will do but categories tree above is only simple exmapmle. But I am seek for more universal and if it possible standard way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.