I was looking for a quick and dirty way of converting JSON into some simple groovy objects that I have. The method recursively walks the object hierarchy and then populates corresponding values that are present in the JSON. Enjoy!
/**
* Slick way of using reflection to populate value
* objects with JSON. Performs a DEEP copy in order
* to populate all of the dependent pogo properties
*
* @param obj object to populate - pogo
* @param json grails.converters.deep.JSON
* @return the obj param
*/
protected def populateFromJson(def obj, def json) {
obj.metaClass.properties.each {metaBeanProperty ->
if (metaBeanProperty.modifiers == Modifier.PUBLIC) {
def val = null
String jsonVal = json[metaBeanProperty.name]
if (metaBeanProperty.type == String) {
val = jsonVal
} else if (Number.isAssignableFrom(metaBeanProperty.type)) {
if (jsonVal?.isNumber()) val = jsonVal.invokeMethod("to${metaBeanProperty.type.simpleName}", null)
} else if (metaBeanProperty.type == Date) {
if (jsonVal) val = Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", jsonVal)
} else if (metaBeanProperty.type == Boolean) {
if (jsonVal) val = jsonVal.toBoolean()
} else if (metaBeanProperty.type.name.startsWith("com.mycomp")) {
val = populateFromJson(metaBeanProperty.type.newInstance(), json[metaBeanProperty.name])
}
obj[metaBeanProperty.name] = val
}
}
return obj
}

1 comments:
At least I can consider this the best candidate to the best method ever.
Explendid!!!
Post a Comment