If I have a simple object such as
class Person {
String name
Integer age
}
I can easily render it's user-defined properties as JSON using the JSONBuilder
def person = new Person(name: 'bob', age: 22)
def builder = new JSONBuilder.build {
person.properties.each {propName, propValue ->
if (!['class', 'metaClass'].contains(propName)) {
// It seems "propName = propValue" doesn't work when propName is dynamic so we need to
// set the property on the builder using this syntax instead
setProperty(propName, propValue)
}
}
def json = builder.toString()
This works fine when the properties are simple, i.e. numbers or strings. However for a more complex object such as
class ComplexPerson {
Name name
Integer age
Address address
}
class Name {
String first
String second
}
class Address {
Integer houseNumber
String streetName
String country
}
Is there a way that I can walk the entire object graph, adding each user-defined property at the appropriate nesting level to the JSONBuilder?
In other words, for an instance of ComplexPerson
I would like the output to be
{
name: {
first: 'john',
second: 'doe'
},
age: 20,
address: {
houseNumber: 123,
streetName: 'Evergreen Terrace',
country: 'Iraq'
}
}
Update
I don't think I can use the Grails JSON converter to do this because the actual JSON structure I'm returning looks something like
{ status: false,
message: "some message",
object: // JSON for person goes here
}
Notice that:
- The JSON generated for the
ComplexPerson
is an element of a larger JSON object
- I want to exclude certain properties such as
metaClass
and class
from the JSON conversion
If it's possible to get the output of the JSON converter as an object, I could iterate over that and remove the metaClass
and class
properties, then add it to the outer JSON object.
However, as far as I can tell, the JSON converter only seems to offer an "all or nothing" approach and returns it output as a String
See Question&Answers more detail:
os