1

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.