Search code examples
mysqljsongrailsgroovygrails-orm

Marshaling mysql string column that contains json string to object in groovy


I am new to groovy Grails and trying to understand how to work with GORM

We have SQL table with column of string type that holds JSON String representing some object (I can't alternate db design)

I understand that in groovy Model objects represent SQL records and in general we can use marshallers to render objects to JSON

But what I need is to get, create or save Model object that have Json string column that will be rendered to an object in groovy, but can't find any information on how to do it

for example to simplify i will have following table : id(number), json(longstring) and in JSON:

{"name":"object1", "list":[{"item":"item1", "type":"type1"},{"item":""item2", "type":"type2"},..]}

and following classes:

class MainModelClass {
Long id
MyObject o
...

}

class MyObject {
List<Item> items
...
}

class Item {
String item
String type
...
}

How can I make the Model object parse the JSON to Object structure

Thanks


Solution

  • You could use a simple trick with a transient property like so:

    import groovy.json.*
    
    class MainModelClass {
    
       String originalJson
    
       static final JsonSlurper slurper = new JsonSlurper()
    
       MyObject getMyObject(){
         slurper.parseText( originalJson ) as MyObject
       }
    
       void setMyObject( MyObject myObject ){
         originalJson = JsonOutput.toJson myObject
       }
    
       static transients = [ 'myObject' ]
    
    }
    

    You might want to use Jackson Mapper to have finer control over marshalling.