3

I want to parse a json object in java.The json file is {"l1":"1","l2":"0","f1":"0","connected":"0","all":"0"} i am trying to write a java program to print above json as

l1=1
l2=0
f1=0
connected=0
all=0

The number of entries in the json file can be increased, so i have to loop through the json and print all data. This is what i've done so far.

public class main {
    public static void main(String[] args){
        try{
            URL url = new URL("http://localhost/switch.json");
            JSONTokener tokener = new JSONTokener(url.openStream());
            JSONObject root = new JSONObject(tokener);
            JSONArray jsonArray = root.names();
            if (jsonArray != null) { 
               int len = jsonArray.length();
               for (int i=0;i<len;i++){ 
                  System.out.println(jsonArray.get(i).toString());
               } 
            }   
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error Occured");
        }
    }
}

the above program can only print the first item of each array. But i am trying get the result i mentioned in the beginning. Can anybody help ??

5
  • I am using a library from json.org. Commented Mar 2, 2015 at 9:21
  • 1
    Show us an example of such a JSON array. Right now you parse an object, not an array. Show us the code you use to parse an array of objects. Commented Mar 2, 2015 at 9:22
  • i just want to parse this {"l1":"1","l2":"0","f1":"0","connected":"0","all":"0"}. I have added the code used in the question. Commented Mar 2, 2015 at 9:25
  • 1
    If it starts with { and ends with }, that is a JavaScript/JSON Object, not an Array; JavaScript Arrays use [ and ], and do not need : to separate keys and values. Commented Mar 2, 2015 at 9:26
  • Sorry ive edited the question. Commented Mar 2, 2015 at 9:29

2 Answers 2

4

It is simple JSON object, not an array. You need to iterate through keys and print data:

    JSONObject root = new JSONObject(tokener);
    Iterator<?> keys = root.keys();

    while(keys.hasNext()){
        String key = (String)keys.next();
        System.out.println(key + "=" + root.getString(key));
    }

Please note that above solution prints keys in a random order, due to usage of HashMap internally. Please refer to this SO question describing this behavior.

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

3 Comments

error : can only iterate over an array or any instance or java.lang.iterable
Why the array is printing in random order ?? I got output as connected=0 all=0 l1=1 l2=1 f1=0
Because values are stored in a HashMap internally, so keys are not ordered.
4

Your JSON file does not contain an array - it contains an object.

JSON arrays are enclosed in [] brackets; JSON objects are enclosed in {} brackets.

[1, 2, 3]                     // array
{ one:1, two:2, three:3 }     // object

Your code currently extracts the names from this object, then prints those out:

JSONObject root = new JSONObject(tokener);
JSONArray jsonArray = root.names();

Instead of looping over just the names, you need to use the names (keys) to extract each value from the object:

JSONObject root = new JSONObject(tokener);
for (Iterator<?> keys= root.keys(); keys.hasNext();){
  System.out.println(key + "=" + root.get(keys.next()));
}

Note that the entries will not print out in any particular order, because JSON objects are not ordered:

An object is an unordered set of name/value pairs -- http://json.org/

See also the documentation for the JSONObject class.

2 Comments

error : can only iterate over an array or any instance or java.lang.iterable
It's the same error, but I didn't see your answer until afterwards, so too late to avoid! Shame the library doesn't implement Iterable...

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.