使用插值将字符串添加到带有变量的groovy映射中 [英] Adding a string to a groovy map with a variable using interpolation

查看:160
本文介绍了使用插值将字符串添加到带有变量的groovy映射中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码:

 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)

并输出

{

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

    "title":     {

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

        "strings":         [

            "Release ",

            ""

        ],

        "valueCount": 1,

        "values": ["v1.0.2"]

    }

}

为什么指定as String会更改输出以使插值有效,但如果没有此操作,则输出似乎是某种复杂类型.

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.

推荐答案

当在字符串中使用$替换其中的变量时,实际上并没有获得Java String,而是GString.然后,您的JSON序列化器将序列化为该序列号:

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]

在消费者接受任何对象的地方,经常需要使用.toString()或将其强制转换为String,因此有所作为.根据您的JSON-Library,为GString添加自己的序列化程序可能是个好主意,以防止此类混淆.

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.

这篇关于使用插值将字符串添加到带有变量的groovy映射中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆