json - 如何使用具有变量名称的键和具有其值的值的 JsonBuilder 构造 json?

标签 json groovy jsonbuilder

如何使用具有相同名称的键和值的 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_iduserId但同样,它与我遵循的其他约定不一致。所以我正在寻找一种优雅的方法和原因 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()
    
  • 如果您需要 JSON 看起来像 {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()
    
  • 只是为了 groovy 脚本,您可以删除 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/

    相关文章:

    grails - 无法保存域类实例;获取类型不匹配错误

    arrays - Groovy 简单 JSON 数组生成器

    json - 在Groovy中使用多个数组构建JSON

    json - 创建一个 JSON 对象以在 Spring Boot 测试中发布

    php - 运行 PHP 脚本,无需网页等待其完成

    android - 无法在空对象上获取属性 'kotlinOutputDir' - Kotlin 和 Spock

    java - 使用 Oracle SQL/JSON 进行深度扫描

    php - json_encode 给出递归错误

    groovy - 在 SoapUI groovy 脚本中获取上一个测试步骤的名称