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!

3
  • 2
    Try it this way: {"names":["JACK","JILL","JOHN","JENNY","JAMES","JIM"]} Commented Mar 14, 2011 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. Commented Mar 14, 2011 at 20:15
  • Thanks, BalusC. Just removed the exception handling to minimize the code. Commented Mar 14, 2011 at 20:37

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.