【问题标题】:Adding a string to a groovy map with a variable using interpolation使用插值将字符串添加到带有变量的 groovy 映射
【发布时间】:2018-11-16 14:48:33
【问题描述】:

考虑代码:

 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 会更改输出,以便插值有效,但如果没有这个,输出似乎是某种复杂类型。

【问题讨论】:

    标签: groovy


    【解决方案1】:

    当您在字符串中使用$ 来替换其中的变量时,您实际上并没有得到一个Java 字符串,而是一个GString。然后,您的 JSON 序列化程序只是将其序列化:

    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() 或强制转换为字符串,因此这会有所不同。根据您的 JSON-Library,为 GString 添加您自己的序列化程序以防止出现此类混淆可能是个好主意。

    【讨论】:

      猜你喜欢
      • 2017-01-09
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2017-04-03
      • 2012-08-21
      • 2012-12-25
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多