Reputation: 13173
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?
Upvotes: 3
Views: 3488
Reputation: 3801
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
)
}
}
}
Upvotes: 2
Reputation: 171184
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
Upvotes: 0
Reputation: 187399
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.
Upvotes: 0