2

I new to parsing JSON - up until this point, I've been purely XML. Anyways, I am using JSON (Java ME) to parse something with the following structure:

{"name" : "JACK","name" : "JILL","name" : "JOHN","name" : "JENNY","name" : "JAMES","name" : "JIM"}

Here is my code:

    try {
        JSONObject json = new JSONObject(response);
        JSONArray jsonArray = outer.getJSONArray("name");
        System.out.println("ARRAY SIZE:"
                + jsonArray.length());
    } catch (JSONException ex) {
    }

My problem is that I cannot even get the println("ARRAY SIZE:"...) statement to output at all in my Eclipse console. The only time that I am getting any sort of output is if I use the following code:

try {
        JSONObject json = new JSONObject(response);
        System.out.println("OUTPUT:"
                + json.getString("name"));
    } catch (JSONException ex) {
    }

...That seems to give me only the last element. Is there a reason why I cannot get the JSONArray to work? Is it because the JSON contains no "outer" key?

I'd appreciate any help. Thanks!

littleK
  • 19,521
  • 30
  • 128
  • 188
  • 2
    Try it this way: `{"names":["JACK","JILL","JOHN","JENNY","JAMES","JIM"]}` – Oleh Prypin Mar 14 '11 at 20:10
  • A general hint in Java programming: don't suppress/swallow exceptions. Just throw them or at least print them by `ex.printStackTrace()`. They contain invaluable information about the cause of the problem. – BalusC Mar 14 '11 at 20:15
  • Thanks, BalusC. Just removed the exception handling to minimize the code. – littleK Mar 14 '11 at 20:37

2 Answers2

3

The key must be unique. You need to differentiate those "name"'s by using "Name1", "Name2", ... etc

zs2020
  • 53,766
  • 29
  • 154
  • 219
  • Unfortunately, the JSON is being returned by a web service out of my control. I will have to take it up with them. Good to know, though - thanks! – littleK Mar 14 '11 at 20:38
0

Hey Hi create one json file like format.... {"name1" : "JACK","name2" : "JILL","name3" : "JOHN","name4" : "JENNY","name5" : "JAMES","name6" : "JIM"} & save this file in WEB-INF Folder on server & get response from server with reading this file... Thanks

Mr. Sajid Shaikh
  • 7,051
  • 4
  • 21
  • 35