在groovy中,如何将映射键的值分配给字符串
我编写了一个方法(如下所述),它返回一个映射在groovy中,如何将映射键的值分配给字符串,groovy,hashmap,key,Groovy,Hashmap,Key,我编写了一个方法(如下所述),它返回一个映射 Class MyTest static Map<String, String> getApplicationPreferences() { String host = System.getProperty("property1") String namespace = System.getProperty("property2") String username = System.getProperty("prop
Class MyTest
static Map<String, String> getApplicationPreferences() {
String host = System.getProperty("property1")
String namespace = System.getProperty("property2")
String username = System.getProperty("property3")
String password = System.getProperty("property4")
String url = "http://" + host + ":10000/v3/namespaces/" + namespace + "/apps/MyApplication/preferences"
String token = RestUtil.getToken(host, username, password)
HttpURLConnection connection = RestUtil.sendRequest(url, token, true, RestUtil.REQUEST_METHOD.GET)
String response = connection.getInputStream().getText()
Map<String, String> preferences = new ObjectMapper().readValue(response, Map.class)
return preferences
}
现在我想把这些值赋给字符串变量,这些变量必须传递给另一个函数
static String a = envPreferences.get('messaging.kafkaBrokers')
println("Kafka preferences="+a)
static String b = envPreferences.get("zookeeper.server").toString()
println("Zookeeper preferences="+b)
我得到的上述打印语句的输出是:
All preferences=[zookeeper.server:localhost:2181, messaging.kafkaBrokers:localhost:9092]
Kafka preferences=null
Zookeeper preferences="null"
如何获取值而不是null?
提前感谢。您的代码有点“javaish”(而不是groovyish),但一般来说,这是从映射中获取该字符串值的方法。所以这里的一个解释可能是,不管这些地图中的键是什么,它们都像字符串一样打印,但它们不是。您可以尝试
println(envPreferences.inspect())
或询问键的类型(或使用调试器)。我关心的一件事是输出和打印之间的差异。例如,Zookeeper preferences=“null”
表示Zookeeper.server
的值为“null”。那些是CnP错误吗?奇怪的是,envPreferences
声明为static
,并用空映射初始化。我不确定它是在静态上下文中分配的envPreferences=MyTest.getApplicationPreferences()
。我们看不到全貌。您能否提供声明和使用的脚本或类?envPreferences
有很多代码,不清楚您遇到了什么特殊问题。你能提供一个最小的可重复的例子,并澄清你到底有什么问题?
static String a = envPreferences.get('messaging.kafkaBrokers')
println("Kafka preferences="+a)
static String b = envPreferences.get("zookeeper.server").toString()
println("Zookeeper preferences="+b)
All preferences=[zookeeper.server:localhost:2181, messaging.kafkaBrokers:localhost:9092]
Kafka preferences=null
Zookeeper preferences="null"