英文:
Groovy read json-file, add new key : value and write back (Jenkins)
问题
Here's the translated code snippet without the translation of the error message:
我想要从文件中读取一个JSON字符串,添加一个新的键值对,然后将其写回文件中,使用Groovy脚本在Jenkins构建过程中。
文件:
```json
{"key1": "value1", "key2": "value2"}
我尝试了以下方法:
def setValue(String filepath, String key, value){
String fileContent = readFile(filepath)
Map jsonContent = (Map) new JsonSlurper().parseText(fileContent)
jsonContent.put("${key}", "${value}")
writeFile(file: filepath, text: JsonOutput.toJson(jsonContent))
}
这是您请求的代码翻译部分。如果您需要更多帮助,请随时提出。
<details>
<summary>英文:</summary>
I want to read a json string out of a file, add a new key : value and write it back to the file.
with groovy-script during Jenkins-build.
file:
```json
{"key1": "value1", "key2": "value2"}
I tried the following:
def setValue(String filepath, String key, value){
String fileContent = readFile(filepath)
Map jsonContent = (Map) new JsonSlurper().parseText(fileContent)
jsonContent.put("${key}", "${value}")
writeFile(file: filepath, text: JsonOutput.toJson(jsonContent))
}
but getting the following error:
exception: class java.io.NotSerializableException
[Pipeline] echo
message: groovy.json.internal.LazyMap
答案1
得分: 1
您可以使用描述在这里的readJson
和writeJson
函数。
Jenkins不时将流水线的状态备份,以便在发生故障时能够恢复它。在此备份步骤期间,它尝试对流水线当前上下文中的每个元素进行序列化。NotSerializableException
通知您在上下文(堆栈或堆)中存在一个不可序列化的对象,这会阻止流水线被序列化。因此,请尽量只使用可序列化的对象。如果不可能,您可以使用@NonCPS
注释标记使用此类对象的函数,以告诉Jenkins在执行该函数期间不要尝试备份流水线。
英文:
Quick answer
You can use the functions readJson
and writeJson
as described here.
Long answer
Jenkins from time to time backs up the status of the pipeline to be able to resume it in case of failure. During this backup step, it tries to serialize every element in the current context of the pipeline. NotSerializableException
notifies you that you have a not serializable object in your context (stack or heap) which prevents the pipeline from being serialized. Therefore try to only use serializable objects. If it is not possible, you can annotate functions that use such objects with @NonCPS
to tell Jenkins not to atempt to back up the pipeline during the execution of that function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论