【问题标题】:Creation of dynamic payload in groovy script在 groovy 脚本中创建动态有效负载
【发布时间】:2018-01-10 07:25:13
【问题描述】:

我必须使用 groovy 创建一个 json 有效负载,就像 -

{
  "source":1,
  "target":0 
}

源值和目标值将从 0 开始动态变化。你能帮我解决这个问题吗?

【问题讨论】:

  • 你试过解决方案了吗?

标签: json groovy jsonbuilder


【解决方案1】:

您可以使用JsonBuilder创建所需的json,如下所示。

//Define value or assign it dynamically for target and source as shown below
def tValue = 0
def sValue = 1

def json = new groovy.json.JsonBuilder()
json {
  source sValue
  target tValue
}
println json.toPrettyString()

大家可以在线快速试用demo

【讨论】:

    【解决方案2】:

    通常很好用 JsonOutput。您可以从地图构建 json:

    def map = [source:1, target:0]
    def out = new groovy.json.JsonOutput()
    println out.prettyPrint(out.toJson(map))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多