我正在尝试从JSON字符串读取键和值。我也不知道键,因此无法基于键检索值。我将不得不分别阅读键和值。
JsonObject jsonObject = new JsonParser().parse(vaultJson).getAsJsonObject()
vaultData = jsonObject.get("data").asJsonObject
println "########################"
println "vault data as json object"
println vaultData //{"key1":"key1_val1","key2":"key2_val2"}
println "########################"
for(Object data : vaultData.entrySet()){
println data
println "in for loop"
//I m looking for something like, data.getKey and data.getValue
}
//OUTPUT of for loop
key1="key1_val1"
in for loop
key2="key2_val2"
in for loop
{"request_id":"7d64a2b3-ac8b-9acf-e219-4686e8577fda","lease_id":"","renewable":false,"lease_duration":2764800,"data":{"key1":"key1_val1","key2":"key2_val2"},"wrap_info":null,"warnings":null,"auth":null}
如何在单独的字符串中读取key1
和key1_val1
?在使用分割字符串方法之前,我想检查gson中是否有内置函数可以执行此操作。 最佳答案
为什么不简单地:
import groovy.json.*
Map json = new JsonSlurper().parseText('{"request_id":"7d64a2b3-ac8b-9acf-e219-4686e8577fda","lease_id":"","renewable":false,"lease_duration":2764800,"data":{"key1":"key1_val1","key2":"key2_val2"},"wrap_info":null,"warnings":null,"auth":null}')
json.each{ key, val ->
println "$key -> $val"
}
版画request_id -> 7d64a2b3-ac8b-9acf-e219-4686e8577fda
lease_id ->
renewable -> false
lease_duration -> 2764800
data -> [key1:key1_val1, key2:key2_val2]
wrap_info -> null
warnings -> null
auth -> null