0

I have a json object how can I get all the keys and later without hard coding the keys how can I get the key values.

  {  
     "A":"M1",
     "Data":[  
        {  
           "B":[  
              {  
                 "B1":"111",
                 "B2":"Warning "

              },
              {  
                 "B1":"222",
                 "B2":"Warning "

              }
           ],
           "C":[  
              {  
                 "c1":"IL2",
                 "c2":"[0.750183,0.00933380975964486]"
              },
              {  
                 "c1":"IL1b",
                 "c2":"[0.750183,-1.5216938335421]"
              }
           ]
        }
     ]
  }
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
1209
  • 159
  • 1
  • 3
  • 10
  • 3
    possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – Manwal Nov 21 '14 at 04:40
  • Please refer the following link which may help you [Accessing elements of JSON object without knowing the key names][1] [1]: http://stackoverflow.com/questions/5113847/accessing-elements-of-json-object-without-knowing-the-key-names – ABI Nov 21 '14 at 04:43
  • jackson is really nice api to deal with json strings. It allows to parse json directly in pojo or any desired objects. It has lots of flexibility to deal with json. Refer http://jackson.codehaus.org/ for more details. – Gaurav Nov 21 '14 at 05:03
  • @amrutha [This](http://ankursinghal86.blogspot.jp/2014/11/json-to-hashmap-parsing-json-string.html) might help, just wrote now for you. – Ankur Singhal Nov 21 '14 at 05:12
  • @amrutha Did you have a look on article, did it solve your purpose. Once you get HashMap, iterate over it for `entry.getKey()` and `entry.getValue()` – Ankur Singhal Nov 21 '14 at 05:19
  • Hi Aukur it helped me a lot.Thank you Any option to get the current key and the previous key – 1209 Nov 21 '14 at 08:24
  • Ankur if my json is as below – 1209 Nov 23 '14 at 00:53

1 Answers1

0

Try this out... This might work for you....

You have to use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

Roughly the code will look like:

// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();

while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();

    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

    // do something here with the value...
}
Salmaan
  • 3,543
  • 8
  • 33
  • 59
  • I am using import org.json.JSONObject; is that fine or any other jar i am suppsoe to use – 1209 Nov 21 '14 at 05:13