7

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.

David
  • 7,652
  • 21
  • 60
  • 98

2 Answers2

15

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)
David
  • 7,652
  • 21
  • 60
  • 98
  • readJSON text: '{}' throws the following `No such constructor found: new java.lang.String net.sf.json.JSONObject net.sf.json.JSONObject net.sf.json.JSONObject`. Jenkins version 2.190.2 – Cristian G Jan 16 '20 at 14:45
0

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)