【问题标题】:Parse JSON data, and write the data to a file using groovy解析 JSON 数据,并使用 groovy 将数据写入文件
【发布时间】:2019-03-18 00:31:11
【问题描述】:

这里我们将 1234 中的“dpidsha1”值替换为 json 内容中的另一个值“abcd”,并且 我们正在尝试 将json格式的内容写入文件“uselessfile.json”,并打印文件“uselessfile.json”的内容

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def buildContent(){


def content = """
{
   "app":{ },
   "at":2,
   "badv":[ ],
   "bcat":[ ],
   "device":[ {
      "carrier":"310-410",
      "connectiontype":3,
      "devicetype":1,
      "dnt":0,
      "dpidmd5":"268d403db34e32c45869bb1401247af9",
      "dpidsha1":"1234" 
   },
   {
      "carrier":"310-410",
      "connectiontype":3,
      "devicetype":1,
      "dnt":0,
      "dpidmd5":"268d403db34e32c45869bb1401247af9",
      "dpidsha1":"1234" 
   }]
}"""

def slurped = new JsonSlurper().parseText(content)
def builder = new JsonBuilder(slurped)
builder.content.device.dpidsha1 = 'abcd'  
println(builder.toPrettyString())

writeFile file: 'uselessfile.json', text: builder.toPrettyString(content)

  File file = new File("uselessfile.json")

  println "Below is the content of the file ${file.absolutePath}"
  println uselessfile.json

错误:

[管道] 管道结束 发生的异常: 在字段 com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals

原因:java.io.NotSerializableException:groovy.json.JsonBuilder

【问题讨论】:

  • jsonBuilder.toPrettyString(content) 应该是builder.toPrettyString(content)
  • 将数据写入 uselessfile.json 文件时仍然失败。我已经更新了问题。

标签: jenkins groovy jenkins-pipeline jenkins-groovy


【解决方案1】:

您可以使用pipeline utility steps readJSONwriteJSON 来归档您的目标,如下所示:

def buildContent(){

   def content = """
      {
         "app":{ },
         "at":2,
         "badv":[ ],
         "bcat":[ ],
         "device":{
            "carrier":"310-410",
            "connectiontype":3,
            "devicetype":1,
            "dnt":0,
            "dpidmd5":"268d403db34e32c45869bb1401247af9",
            "dpidsha1":"1234" 
         }
      }
   """

   def jsonObj = readJSON text: content.trim()
   jsonObj.device.dpidsha1 = 'abcd'

   writeJSON file: 'uselessfile.json', json: jsonObj, pretty: 4

   sh 'cat uselessfile.json'
}

java.io.NotSerializableException: groovy.json.JsonBuilder 的原因是 Jenkins 流水线会在序列化后存储流水线。但是groovy.json.JsonBuilder类没有实现Serializable,所以不能序列化

【讨论】:

  • 仍然出现错误:未找到此类字段:字段 net.sf.json.JSONArray 版本。我已经更新了问题。
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2017-04-15
  • 2018-05-26
  • 1970-01-01
相关资源
最近更新 更多