Reputation: 589
Here, we are replacing a value of "dpidsha1" from 1234 to another value "abcd" in JSON conent, and Facing an error while writing 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.find{it.dpidsha1}.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
How can I solve this?
Upvotes: 3
Views: 2852
Reputation: 6842
I would prefer to use the Utility functions of the Jenkins Pipelines instead of the groovy classes. The below pipeline works. I have simplified the dumping to screen in the end to verify the result to use the bash cat command. But the result is what you want I think.
node('linux') {
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 = readJSON text: content
println (slurped)
def builder = slurped
builder.device.find{it.dpidsha1 == "1234"}.dpidsha1= "abcd"
println(builder)
writeJSON file: 'uselessfile.json', json: builder, pretty: 4
sh 'cat uselessfile.json'
}
Upvotes: 1
Reputation: 13722
You can add @NonCPS
annotation on your method as following:
@NonCPS
def buildContent(){
...
}
The @NonCPS annotation is useful when you have methods which use objects which aren't serializable. Normally, all objects that you create in your pipeline script must be serializable (the reason for this is that Jenkins must be able to serialize the state of the script so that it can be paused and stored on disk).
When you put @NonCPS on a method, Jenkins will execute the entire method in one go without the ability to pause. Also, you're not allowed to reference any pipeline steps or CPS transformed methods from within an @NonCPS annotated method. More information about this can be found here.
Upvotes: 0