0

Here we are replacing a value of "dpidsha1" from 1234 to another value "abcd" in json conent, and We are trying to write json formatted content to a file "uselessfile.json", and print the content of the file "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

ERROR:

[Pipeline] End of Pipeline an exception which occurred: in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals

Caused: java.io.NotSerializableException: groovy.json.JsonBuilder

2
  • jsonBuilder.toPrettyString(content) should be builder.toPrettyString(content) Commented Mar 18, 2019 at 1:32
  • It still fails while writing the data to uselessfile.json file. I have updated the question. Commented Mar 18, 2019 at 3:03

1 Answer 1

2

You can use pipeline utility steps readJSON and writeJSON to archive your goal as following:

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'
}

The reason of java.io.NotSerializableException: groovy.json.JsonBuilder is Jenkins pipeline will store the pipeline after serialize. But the class groovy.json.JsonBuilder not implement Serializable, thus it's can't be serialized

Sign up to request clarification or add additional context in comments.

1 Comment

Still getting ERROR: No such field found: field net.sf.json.JSONArray version. I have updated the question .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.