David
David

Reputation: 8196

Adding a string to a groovy map with a variable using interpolation

Consider code:

 Map prJsonData = readJSON text: '{}'
 prJsonData.head = "release/${NEW_TAG}" as String
 prJsonData.title = "Release ${NEW_TAG}"
 writeJSON(file: 'create-pr.json', json: prJsonData, pretty: 4)

and output

{

    "head": "release/v1.0.2",

    "title":     {

        "bytes":         [
            82,
            101,
            97
        ],

        "strings":         [

            "Release ",

            ""

        ],

        "valueCount": 1,

        "values": ["v1.0.2"]

    }

}

Why is it that specifying as String changes the output such that interpolation works but without this the output appears to be some sort of complex type.

Upvotes: 1

Views: 1622

Answers (1)

cfrick
cfrick

Reputation: 37008

When you use $ inside a string to replace variables in it, you don't actually get a Java String back, but a GString. Your JSON serializer there then just serializes that instead:

groovy:000> a=1
===> 1
groovy:000> s="$a"
===> 1
groovy:000> s.getClass()
===> class org.codehaus.groovy.runtime.GStringImpl
groovy:000> s.properties
===> [values:[1], class:class org.codehaus.groovy.runtime.GStringImpl, bytes:[49], strings:[, ], valueCount:1]

Using .toString() or casting to a String is often needed where consumers accept any object and so this makes a difference. Depending on your JSON-Library it might be a good idea to add your own serializer for GString to prevent confusion like this.

Upvotes: 8

Related Questions