Persisting Maps and Lists of properties as JSON in Grails Persisting Maps and Lists of properties as JSON in Grails json json

Persisting Maps and Lists of properties as JSON in Grails


For option 2, you can use the beforeValidate event instead of beforeInsert and beforeUpdate events to ensure that the change propagates correctly.

class ClassWithComplexProperties {  Map complexMapStructure //not persisted  String complexMapStructureAsJSON //updated and synched with map via onload,beforeInsert,beforeUpdate  static transients = ['complexMapStructure']  def onLoad() {    complexMapStructure=JSON.parse(complexMapStructureAsJSON)  }// >>>>>>>>>>>>>>  def beforeValidate() {    complexMapStructureAsJSON= complexMapStructure as JSON  }// >>>>>>>>>>>>>>  static constraints = {        complexMapStructureAsJSON( maxSize:20000)  }}


I of course do not know much about the application you are building, but it won't hurt to look up alternate data storage models particularly NOSQL databases. Grails has got some support for them too.


Is there a simpler approach to persist my complex, dynamic map data?

Grails can persist List and Map out of the box, you don't need to write complex conversion code and abuse Json.

Example for Map:

class ClassWithComplexProperties {    Map<String, String> properties    }def props = new ClassWithComplexProperties()props.properties = ["foo" : "bar"]props.save()

Example for List:

class ClassWithComplexProperties {    List<String> properties    static hasMany = [properties: String]}def props = new ClassWithComplexProperties()props.properties = ["foo", "bar"]props.save()

I think this is much easier and cleaner way how to deal with it.