首页 > 解决方案 > 如何使用 JsonBuilder 在 Groovy 中创建一个简单的 JSON?

问题描述

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 完全陌生。

标签: jsongroovy

解决方案


您可以简单地使用 a并使用辅助方法Map将其呈现为 JSON ,例如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 文档并在需要时对其进行操作。


推荐阅读