[英]Executing Groovy script from JSON
If I want to send multiline string in JSON using curl the only way is to concatenate string using spaces. 如果要使用curl在JSON中发送多行字符串,唯一的方法是使用空格连接字符串。 So this is working. 所以这是工作。 But what to do if I send groovy script which will be run? 但是,如果我发送将要运行的groovy脚本怎么办? Like in content property: 就像在内容属性中一样:
{
"name": "helloWorld",
"content": "repository.createDockerHosted('docker_private', 8082_1, null) repository.createDockerHosted('docker_private_2', 8082, null)",
"type": "groovy"
}
Is it possible to inform groovy compiler that there are two instructions? 是否可以通知groovy编译器有两条指令? Maybe by adding some special character to content value? 也许通过在内容值中添加一些特殊字符?
Thanks for help :) 感谢帮助 :)
To execute a string as Groovy script, the standard pattern is to use GroovyShell
with a Binding
: 要将字符串作为Groovy脚本执行,标准模式是将GroovyShell
与Binding
:
class Repository {
def createDockerHosted(a, b, c) {
println "TRACER createDockerHosted $a $b $c"
}
}
def content = "repository.createDockerHosted('docker_private', 8082_1, null) ; repository.createDockerHosted('docker_private_2', 8082, null)"
def binding = new Binding()
binding.setProperty('repository', new Repository())
def shell = new GroovyShell(binding)
shell.evaluate(content)
(Note in the above that content
has ;
to separate the two statements) Output: (在上面请注意, content
具有;
分隔两个语句)输出:
$ groovy Example.groovy
TRACER createDockerHosted docker_private 80821 null
TRACER createDockerHosted docker_private_2 8082 null
So for your situation (if I understand it), the only issue is how to extract content
from JSON: 因此,对于您的情况(如果我理解的话),唯一的问题是如何从JSON提取content
:
def jsonStr = '''
{
"name": "helloWorld",
"content": "repository.createDockerHosted('docker_private', 8082_1, null) ; repository.createDockerHosted('docker_private_2', 8082, null)",
"type": "groovy"
}
'''
def jsonMap = new groovy.json.JsonSlurper().parseText(jsonStr)
def content = jsonMap['content']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.