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

狂风中的少年 提交于 2019-12-04 00:51:10
  • Declare accessors for the variable userId, if you need the JSON to look like {userId:12}

as

import groovy.json.JsonBuilder

def getUserId(){
    def userId = 12 // some user id obtained from else where.
}

def json = new JsonBuilder()
def root = json{
    userId userId
}
print json.toString()
  • If you need the JSON to look like {12:12} which is the simplest case:

then

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()
  • Just for the sake of the groovy script you can remove def from userId to get the 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 also be used as map keys (which is String by 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"}
import groovy.json.JsonBuilder
def userId = "12" // some user id obtained from else where.
def json = new JsonBuilder([userId: userId])
print json.toString()

I was able to get a desired output using a different param to JsonBuilder's call() method. i.e., instead of passing in a closure, pass in a map.

Use def call(Map m) instead of def call(Closure c).

import groovy.json.JsonBuilder

long userId = 12
long z = 12
def json = new JsonBuilder()

json userId: userId,
     abc: 1,
     z: z     
println json.toString()    //{"userId":12,"abc":1,"z":12}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!