1

Sample JSON:

{"xyz":{"string":"hello"},"abc":{"string":"rts","event":"file","value":"100"}}

Suppose these are the values present in my JSON file, how do I get the value of the key "event" present in these.

PS: The objects are not separated by commas, and obj in the below code is the object that is created after parsing,

JSONObject jsonObject = (JSONObject) obj;

JSONObject jsonObject1 = (JSONObject) jsonObject.get("abc");
String eventType=(String)jsonObject1.get("event");

This is the code I have used, but I know this is not the optimal solution as the file which I may receive could have objects with other name.

I want to parse all the values in the json file at a time, and get the value, without creating objects for individual records present inside them.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    So what's special about "event" rather than "value" or "string"? If you could receive objects which use a different key, what's special about that key that would allow you to tell the difference between that and other keys? It's also not clear what this has to do with counting. – Jon Skeet Sep 09 '15 at 06:04
  • What JSON library are you using? – MadProgrammer Sep 09 '15 at 06:06
  • @JonSkeet: I'm sorry but i'm new to JSON and this is a part of my assignment. The JSON record which I posted above is just an example. I just want to retrieve the value of the key "event" from this. Can you please help me out. – vishnu reddy Sep 09 '15 at 08:56
  • @MadProgrammer: I'm using json_simple-1.1 jar – vishnu reddy Sep 09 '15 at 09:02
  • @vishnureddy `JSONObject` has a `keyset`(?) method I believe, which will give you the "keys" to all the subsequent objects (of what ever types they might be) – MadProgrammer Sep 09 '15 at 09:33
  • I have a question here. If we don't have a record identifier in any of the document like if "abc" or "xyz" how does the count work? – Karthi Jun 28 '17 at 14:30

1 Answers1

0

In your Json file have Json arrays. Inside of these arrays contains Json objects. So first you can should access array and count the objects using for loop. or you can count the array size using this method JSONArray.size()