I'm trying to convert Grails domain objects to Map. I have a code that do it for POGOs using Apache Commons BeanUtils' PropertyUtils.describe
. However, using the same code on domain objects just doesn't work because of all the stuff added by the Grails framework. I want to be able to convert any object to a Map with only the declared fields just like how Grails converts domain objects to JSON. What features can help me achieve this?
Asked
Active
Viewed 1,597 times
1

Psycho Punch
- 6,418
- 9
- 53
- 86
-
1Does `domainObject.domainClass.persistedProperties` get you closer? – tim_yates Feb 24 '15 at 13:37
-
It could, but I'm looking for a more general solution that works on (almost) any Groovy object in the application. Something like bypassing all the features added by Groovy, and Grails. – Psycho Punch Feb 24 '15 at 13:43
-
1Not sure you can, due to the different way properties are handled... The groovy way (afair) is do do something like `domainObject.class.declaredFields.findAll { !it.synthetic }.name` but I'm not sure how that would work with Grails domain classes or dynamically added properties – tim_yates Feb 24 '15 at 14:20
-
I'll test that. Is there a way to create a temporary domain class just for testing? Will something like `class MyClass implements GrailsDomainClass` do? I want to create a Spec that doesn't get affected when any of my actual domain classes changes. – Psycho Punch Feb 24 '15 at 14:41
1 Answers
0
I would suggest something like this inside your domain class:
public Map asMap() {
this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
[ (it.name):this."$it.name" ]
}
}
There are other questions about the same problem, did you try this? Grails / Groovy - Domain Object - Map of its Properties

Community
- 1
- 1

David Ruiz
- 96
- 3