json - 如何使用 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 完全陌生。
解决方案
您可以简单地使用 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 文档并在需要时对其进行操作。
推荐阅读
- docker - 如何知道 Pod 内的外部端点或 Loadbalancer Service 的 ip
- excel - 计算字段
- c# - 如何在其他循环函数中获取“FileSystemWatcher”的值
- amazon-web-services - Redshift UDF 逻辑问题
- ruby-on-rails - 通过 rails 5.2 中的主动存储将文件和图像上传到 Amazon-S3
- android - 从android中的firebase数据库向多个号码发送消息
- ios - 如果两个单词合适,则将它们放在同一行,如果不合适,则将它们放在新行中
- sql - SQL - ORDER BY Timestamp Array 数据不起作用
- pandas - 针对不同类别的其他列 pandas 和 seaborn 或 matplotlib 的 Groupby 逐年绘图
- c++ - 如何获取 Qt C++ 中所有可用主题的列表?