如何使用具有相同名称的键和值的 JsonBuilder 构造 json?
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()
产生错误
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)
引用键没有任何效果。任何想法如何使这项工作。
编辑:
我希望 JSON 像
{ userId: 12 }
.另外,为什么将 key 写为字符串不起作用?long userId = 12
def json = new JsonBuilder()
def root = json {
"userId" userId
}
提供的示例只是一个片段。情况是我有很多 Controller Action ,其中已经有各种变量。现在我正在添加一个部分,我试图在其中创建一个 JSON 字符串,其中包含变量保存的各种值。所以改变现有的变量名不是很实用,如果我可以构造同名的 JSON 字符串,它会更一致。为我想要的所有变量编写访问器方法也不是一种优雅的方法。我目前所做的是使用不同的命名方案,如
user_id
为 userId
但同样,它与我遵循的其他约定不一致。所以我正在寻找一种优雅的方法和原因 JsonBuilder
以这种方式行事。在 JavaScript 的情况下,
var a = 1
JSON.stringify({a: a}) // gives "{"a":1}"
这是预期的结果。
最佳答案
userId
的访问器, 如果您需要 JSON 看起来像 {userId:12}
作为
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()
{12:12}
这是最简单的情况:然后
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()
def
来自 userId
获得第一个行为。 :) 作为
import groovy.json.JsonBuilder
userId = 12
def json = new JsonBuilder()
def root = json{
userId userId
}
print json.toString()
更新
在构建 JSON 时,局部变量也可以用作映射键(默认为 String)。
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"}
关于json - 如何使用具有变量名称的键和具有其值的值的 JsonBuilder 构造 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19225600/