Vini
Vini

Reputation: 2134

Read key and value from JSON using gson gradle

I m trying to read the key and value from a JSON string. I do not know the key as well so cannot retrieve the value based on the key. I will have to read the key and value separately.

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

Sample JSON

{"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}

How can I read key1 and key1_val1 in separate strings? Before I use a split string method I want to check if there is a builtin function in gson which can do the magic.

Upvotes: 0

Views: 509

Answers (2)

injecteer
injecteer

Reputation: 20707

why not simply:

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"
}

prints

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

Upvotes: 1

Vini
Vini

Reputation: 2134

THis is how I found a way to separate the key and value.

for(Map.Entry<String,JsonObject> data : vaultData.entrySet()){
    println "Key : " + data.key
    String value = data.value.toString()
    println "Value : " + value.replaceAll('^\"|\"$', "")
}

Upvotes: 0

Related Questions