I created a class that allows the resulting object to add arbitrary properties to it. The class also has some predefined properties. In the class method, I want to be able to iterate over all the properties that belong to an instance of an object.
Here is an example of a class definition:
import groovy.json.* class Foo { private Map props = [:] String bar = "baz" def myNumber = 42 void propertyMissing(String name, Object value) { this.props[name] = value } def propertyMissing(String name) { return this.props[name] } def toJsonString() { def outObject = [:]
Is there a way to do what I want to do?
Edit: One of my goals is not to specify explicit predefined properties in the toJsonString method. I want to be able to add new predefined properties later, without thinking about updating the toJsonString method.
Edit (October 24, 2011):
The accepted answer gave me the information I needed. However, I still needed to specify properties that I do not want to include in the JSON string. Extending the answer solves this problem a bit:
def outObject = Foo.declaredFields.findAll { // 'it' is a Field object returned by // http://download.oracle.com/javase/1,5,0/docs/api/java/lang/Class.html
For this to work, you must explicitly specify modifiers for your class properties. That is, String bar = "baz" in my example should be public String bar = "baz" so that it is included in the JSON string.
source share