title: How to construct json using JsonBuilder with key having the name of a variable and value having its value?
body: <p>How to construct json using JsonBuilder with key and value having same name?  </p>
  
  <pre><code>import groovy.json.JsonBuilder
  
  def userId = 12 // some user id obtained from else where.
  
  def json = new JsonBuilder()
  def root = json {
      userId userId
  }
  print json.toString()
  </code></pre>
  
  <p>Which produces the error</p>
  
  <blockquote>
    <p>groovy.lang.MissingMethodException: No signature of method:
    java.lang.Integer.call() is applicable for argument types:
    (java.lang.Integer) values: [12] Possible solutions: wait(), any(),
    abs(), wait(long), wait(long, int), and(java.lang.Number)</p>
  </blockquote>
  
  <p>Quoting the key does has no effect. Any idea how to make this work. </p>
  
  <p>Edit:</p>
  
  <p>I want the JSON to be like <code>{ userId: 12 }</code>. Also, why does writing the key as string not work?</p>
  
  <pre><code>long userId = 12   
  def json = new JsonBuilder()
  def root = json {
      "userId" userId
  }
  </code></pre>
  
  <p>The example provided is just a snippet. The situation is that I have a lot of controller actions, which has various variables already. Now I am adding a part where I am trying to create a JSON string with various values the variables hold. So it's not very practical to change existing variable names and if I could construct the JSON string with the same name, it would be more consistent. Writing accessor methods for all the variables I wanted is also not an elegant method. What I did at present is to use different naming scheme like <code>user_id</code> for <code>userId</code> but again, it's not consistent with rest of the conventions I follow. So I am looking for an elegant approach and the reason why <code>JsonBuilder</code> behaves in this manner.</p>
  
  <p>In case of JavaScript,</p>
  
  <pre><code>var a = 1
  JSON.stringify({a: a})    // gives "{"a":1}"
  </code></pre>
  
  <p>which is the expected result.</p>