abhjt
abhjt

Reputation: 442

Reading the array name itself (not its content) from JSON using java

I have a JSON like this -

result = [ 
       { "value1": [
           { 
             "number" : "3",
             "title" : "hello_world"
           },

           { 
             "number" : "2",
             "title" : "hello_world"
           }
          ]
       },
       { "value2": [
           { 
             "number" : "4",
             "title" : "hello_world"
           },

           { 
             "number" : "5",
             "title" : "hello_world"
           }
          ]
       }
    ]

I want to get result[0] i.e "value1" and result[1] i.e "value2". Below is my code for parsing this Json -

JsonParser jsonParser = new JsonParser();
JsonArray resultArray = jsonParser.parse(result.getAsJsonArray("result"));

Above code is working fine and I am getting 2 Json arrays. Now for getting value1 I have written this code-

String v = resultArray.get(0).getAsJsonObject().get("value1").getAsString();

But this is not giving me value1 rather than its throwing error "java.lang.IllegalStateException". What I am doing wrong here?

Please note that I want to read array name of "value1" and "value2" itself as string and not its inside content.Means print line should print value1 as output.

Upvotes: 0

Views: 59

Answers (1)

nafas
nafas

Reputation: 5423

Value1 is not String but rather a JsonArray,

when you call getAsString() method, it will throw Exception telling you the value is not of a String object.

few Options :

1- read the value as JsonArray then convert it to String using toString method:

String v = resultArray.get(0).getAsJsonObject().getAsJsonArray("value1").toString();

2- use toString method directly on JsonElement itself (return value of get("value1")

String v = resultArray.get(0).getAsJsonObject().get("value1").toString();

I normally use option one because it enforces the check.

EDIT:

After reading comment, basically what is required is to get all the keys of each JsonObject within each Object

you need to loop through the array and get all they entrySet().(not tested but should work)

for(JsonElement element : resultArray){
   JsonObject next= element.getAsJsonObject();
   for(Map.Entry<String,JsonElement> entry : next.entrySet()){
     System.out.println(entry.getKey()); // <-- prints out value1 and value2
   }
}

Upvotes: 2

Related Questions