将 String 解析为 GString 时出错

Error in parsing String to GString

我在我的控制器 class 中使用 groovy

编写了这个 TwiML
"""<?xml version="1.0" encoding="UTF-8"?>
  <Response>
    <Say voice="alice">Dear customer! This  is  an automated call from X_Y_Z.com to intimate  you that the  fare for  your recently  booked  trip from  ${from},to ${to} has increased by,${fare_Difference}$ and now the total fare is,${totalFare}$.</Say>
    <Pause length="1"/>
    <Gather num Digits="1" action="/notify/phone/selection/${phone_Number}/${from}/${to}/${fare_Difference}/${total_Fare}" method="POST" timeout="20" >
        <Say voice="Alice" >To accept the increased fare press 1. To talk to our travel agent press 2. To repeat press 3.</Say><Pause length="3"/>
    </Gather>
  </Response>"""

现在我的团队领导要求我将 TwiML 移至数据库。

这里的问题是我读的时候 从数据库中返回为 java.lang.String(我们在 DAO 层中使用休眠),这是 导致问题,因为它没有评估嵌入值

例如代替 "${from}" 的值 作为 "New York" 它什么都不做,将其保留为 ${from}.

我怎样才能做到这一点?

我尝试将其转换为 GString,但无法实现。

任何帮助将不胜感激。

这是一个已知问题 issue,尚未修复。解决方法是使用 GroovyShell 来评估字符串表达式或使用 GStringTemplateEngine。使用这两种方法的示例代码:

String str = '''
<?xml version="1.0" encoding="UTF-8"?>
  <Response>
    <Say voice="alice">Dear customer! This  is  an automated call from X_Y_Z.com to intimate  you that the  fare for  your recently  booked  trip from  ${from},to ${to} has increased by,${fare_Difference}\$ and now the total fare is,${totalFare}\$.</Say>
    <Pause length="1"/>
    <Gather num Digits="1" action="/notify/phone/selection/${phone_Number}/${from}/${to}/${fare_Difference}/${total_Fare}" method="POST" timeout="20" >
        <Say voice="Alice" >To accept the increased fare press 1. To talk to our travel agent press 2. To repeat press 3.</Say><Pause length="3"/>
    </Gather>
  </Response>
'''


Map bindings = [from: 'Delhi', to: 'Mumbai', fare_Difference: '789', totalFare: '4567', phone_Number: '9876543210', total_Fare: '4567']

println (new GroovyShell(new Binding(bindings)).evaluate ('"""' + str + '"""'))

println new groovy.text.GStringTemplateEngine().createTemplate(str).make(bindings).writeTo(new StringWriter()).toString()

这里要注意的一件事是,如果您想跳过美元符号,那么您可能需要使用双反斜杠 (${fare_Difference}\$) 将其转义。

每种情况下的输出为:

<?xml version="1.0" encoding="UTF-8"?>
  <Response>
    <Say voice="alice">Dear customer! This  is  an automated call from X_Y_Z.com to intimate  you that the  fare for  your recently  booked  trip from  Delhi,to Mumbai has increased by,789$ and now the total fare is,4567$.</Say>
    <Pause length="1"/>
    <Gather num Digits="1" action="/notify/phone/selection/9876543210/Delhi/Mumbai/789/4567" method="POST" timeout="20" >
        <Say voice="Alice" >To accept the increased fare press 1. To talk to our travel agent press 2. To repeat press 3.</Say><Pause length="3"/>
    </Gather>
  </Response>