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

问题描述 投票:0回答:1

这里我们将1234中的“dpidsha1”值替换为json conent中的另一个值“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

错误:

[Pipeline] Endline of Pipeline发生的异常:在字段com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals中

引发:java.io.NotSerializableException:groovy.json.JsonBuilder

jenkins groovy jenkins-pipeline jenkins-groovy
1个回答
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,因此它无法序列化

© www.soinside.com 2019 - 2024. All rights reserved.