代码之家  ›  专栏  ›  技术社区  ›  Benihana

如何使用JsonBuilder在Groovy中创建简单的JSON?

  •  1
  • Benihana  · 技术社区  · 6 年前
    tool_name = 'test
    product_name = 'test'
    platform_name = 'test'
    
    def my_json = new JsonBuilder()
    def root = my_json name: tool_name, product: product_name, platform: platform_name
    print my_json
    

    我做错了什么?我正在尝试创建一个非常基本(平面)的json对象,以便稍后在POST请求中发送。

    类似于:

    {'name': 'test', 'product': 'test', 'platform': 'test'}
    

    最简单的方法是什么?我可以使用JsonBuilder或Slurper进行此操作吗?我对groovy完全陌生。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Szymon Stepniak    6 年前

    您只需使用 Map 并使用 groovy.json.JsonOutput.toJson() 助手方法,例如。

    def tool_name = 'test'
    def product_name = 'test'
    def platform_name = 'test'
    
    def map = [name: tool_name , product: product_name , platform: platform_name]
    
    def json = groovy.json.JsonOutput.toJson(map)
    
    println​ json​
    

    此示例生成以下输出:

    {'name': 'test', 'product': 'test', 'platform': 'test'}
    

    如果要使用 groovy.json.JsonBuilder 然后,下面的示例生成您的预期输出:

    def tool_name = 'test' 
    def product_name = 'test' 
    def platform_name = 'test'
    
    def builder = new groovy.json.JsonBuilder()        
    builder {
        name tool_name
        product product_name
        platform platform_name
    }
    println builder.toString()​
    

    groovy.json.JsonSlurper 类专用于读取JSON文档并在需要时对其进行操作。