groovy - How to construct json using JsonBuilder with key having the name of a variable and value having its value? -


how construct json using jsonbuilder key , value having same name?

import groovy.json.jsonbuilder  def userid = 12 // user id obtained else where.  def json = new jsonbuilder() def root = json {     userid userid } print json.tostring() 

which produces error

groovy.lang.missingmethodexception: no signature of method: java.lang.integer.call() applicable argument types: (java.lang.integer) values: [12] possible solutions: wait(), any(), abs(), wait(long), wait(long, int), and(java.lang.number)

quoting key has no effect. idea how make work.

thanks.

edit:

i want json { userid: 12 }. also, why writing key string not work?

long userid = 12    def json = new jsonbuilder() def root = json {     "userid" userid } 

the example provided snippet. situation have lot of controller actions, has various variables already. adding part trying create json string various values variables hold. it's not practical change existing variable names , if construct json string same name, more consistent. writing accessor methods variables wanted not elegant method. did @ present use different naming scheme user_id userid again, it's not consistent rest of conventions follow. looking elegant approach , reason why jsonbuilder behaves in manner. have opinion groovy 1 disappointing.

in case of javascript,

var = 1 json.stringify({a: a})    // gives "{"a":1}" 

which expected result.

  • declare accessors variable userid, if need json {userid:12}

as

import groovy.json.jsonbuilder  def getuserid(){     def userid = 12 // user id obtained else where. }  def json = new jsonbuilder() def root = json{     userid userid } print json.tostring() 
  • if need json {12:12} simplest case:

then

import groovy.json.jsonbuilder  def userid = 12 // user id obtained else where.  def json = new jsonbuilder() def root = json{     "$userid" userid } print json.tostring() 
  • just sake of groovy script can remove def userid first behavior. :)

as

import groovy.json.jsonbuilder  userid = 12  def json = new jsonbuilder() def root = json{     userid userid } print json.tostring() 

update

local variables can used map keys (which string default) while building json.

import groovy.json.jsonbuilder  def userid = 12  def age = 20 //for example def email = "abc@xyz.com"  def json = new jsonbuilder() def root = json userid: userid, age: age, email: email  print json.tostring() //{"userid":12,"age":20,"email":"abc@xyz.com"} 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -