解析JSON数据,然后使用groovy将数据写入文件

时间:2019-03-18 00:31:12

标签: jenkins groovy jenkins-pipeline jenkins-groovy

在这里,我们将json内容中的 dpi 值从 1234 替换为另一个值“ 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

1 个答案:

答案 0 :(得分: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,因此无法序列化