grails - Groovy - with closure with multiple references -


i'm trying parse json data , assign pojo in grails.

i started

obj.param=jsonrequest.jsonwrap.attrib.something.jsonparam 

after experimenting , refactoring, looks now.

jsonrequest.jsonwrap.attrib.something.with {     obj.param1=jsonparam1     obj.param2=jsonparam2     //...     }   } 

now, can avoid repeated use of obj reference?

i'm imagining actual starting point following. on json side:

import groovy.json.jsonslurper  string jsontext = '''{   "jsonwrap":{     "attrib":{       "something":{         "jsonparam1": "value1",         "jsonparam2": "value2",         "jsonparam3": "value3",         "jsonparam4": "value4",         "jsonparam5": "value5"       }     }   } }'''  def jsonrequest = new jsonslurper().parsetext(jsontext) 

on groovy side:

class objecttype {     def param1, param2, param3, param4, param5 }  def obj = new objecttype() 

now, if had control on how either json side or groovy side defined darnedest ensure property names of json "something" object same property names in groovy "objecttype" class. example, this:

class objecttype {     def jsonparam1, jsonparam2, jsonparam3, jsonparam4, jsonparam5 } 

then, unmarshalling "something" object groovy simple this:

def obj = new objecttype(jsonrequest.jsonwrap.attrib.something) 

only 1 reference json object. 1 reference groovy object. , former used instantiate latter. , furthermore, notice there no need reference properties @ all. is, json objects slurper instances of map, if property names match up, can use default "map constructor" syntax.


if, however, not control property naming in either set of objects, still recommend different map-based short-cut. first define constant map 1 set of property names other, so:

def map = [param1:"jsonparam1", param2:"jsonparam2", param3:"jsonparam3",            param4:"jsonparam4", param5:"jsonparam5"] 

then use object unmarshalling:

def obj = new objecttype().with { o ->     jsonrequest.jsonwrap.attrib.something.with { j ->         map.each { oparam, jparam -> o[oparam] = j[jparam] }     }     o } 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -