Reputation: 8196
I would like to construct a JSON object and write the content to file.
Originally I was inspired by this and tried:
def data = [
a:"test: ${myVar}"
]
writeJSON(file: 'message1.json', json: data)
But this failed with:
Could not instantiate {file=message1.json, json={a=test}} for WriteJSONStep(file: String, json: JSON{}, pretty?: int): java.lang.UnsupportedOperationException: must specify $class with an implementation of interface net.sf.json.JSON
So next I tried:
def data = readJSON text: '{}'
data.a = "test: ${myVar}"
writeJSON(file: 'message1.json', json: data, pretty: 4)
Now the build passes, but the content of the file looks like:
{
"a": {
"bytes": [
114,
101,
108,
101,
97,
115,
101
50
],
"strings": [
"test: ",
""
],
"valueCount": 1,
"values": ["v1.0.2"]
}
}
Whereas my intention was {"a": "test: v1.0.2"}
My end goal is that I want to dynamically construct a JSON object, set some properties with some dynamic data and then write the JSON file.
Is there some syntax that can be used to assign the values as strings, rather than some bytes.
Upvotes: 7
Views: 20227
Reputation: 1
regarding your first attempt, it seems there is a JSONObject.fromObject() function you can use.
def data = JSONObject.fromObject([
a:"test: ${myVar}".toString()
])
writeJSON(file: 'message1.json', json: data)
Upvotes: 0
Reputation: 8196
It seems one solution to this is changing the code that adds to the map to specify as String
:
def data = readJSON text: '{}'
data.a = "test: ${myVar}" as String
writeJSON(file: 'message1.json', json: data, pretty: 4)
Upvotes: 15