0

I am trying to extract the value from a key-value pair in a JSONObect. Here is the structure:

{"key1 ":["dog","cat"],"key2":["house","boat"]}

So, I want to extract the values dog and cat, also values house and boat. I tried the following in Java:

    //obj - has this JSON.

    Iterator iter = obj.keys();
    for (int i=0; i<len; i++){
        String key = (String)iter.next();
        System.out.println("Key is --> "+key);  //This is correctly giving me the keys.
        System.out.println("Value is --> "+clientDetails.getJSONArray(key)); //This is not working. I tried lots of other things but to no avail.

     }

Could somebody please guide me here.

thanks, Kay

kartik
  • 293
  • 4
  • 9

3 Answers3

0

You should use quick-json parser (https://code.google.com/p/quick-json/)

It can be used like this:

 JsonParserFactory factory=JsonParserFactory.getInstance();
 JSONParser parser=factory.newJsonParser();
 Map jsonMap=parser.parseJson(jsonString);

Taken via : How to parse JSON in Java This guy has explained it nicely.

Community
  • 1
  • 1
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
0

I think you are using wrong variable named clientDetails here. you should use same JSON obj here.

The above code is working fine for me with same obj:

String json = "{\"key1 \":[\"dog\",\"cat\"],\"key2\":[\"house\",\"boat\"]}";

JSONObject obj=new JSONObject(json);
Iterator iter = obj.keys();
for (int i=0; i<obj.length(); i++){
    String key = (String)iter.next();
    System.out.println("Key is --> "+key);  
    System.out.println("Value is --> "+obj.getJSONArray(key)); 
}
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • I wonder how it is working for you! Because you are using JSONArray in the last line. JSONArray begins with "[". This is definitely not a JSONArray. – kartik May 19 '15 at 17:38
  • See, Here in JSONObject there are two keys named `key1` and `key2`. and there value pair will be `["house","boat"]` and `["dog","cat"]` respectively. Both are clearly JSON Arrays. So this program will work fine. – Sachin Gupta May 20 '15 at 03:47
0

Thank you for chipping in. I found the answer to my question. Here is how I extracted the value of a JSON which is key value pair, and the value is an array.

Iterator iter = obj.keys();
    for (int i=0; i<len; i++){
        String key = (String)iter.next();
        System.out.println("Key is --> "+key);  
        String[] arr = (String[])clientDetails.get(key); //Here I am extracting the value which is an array, converting it to String array and then  storing it in a variable of type String[]. Now I can loop through this "arr"

for (int m=0; m<arr.length;m++){
       arr[]m  // Can do whatever I want here!
     } 

Thank you guys! -Kay

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
kartik
  • 293
  • 4
  • 9