Alfred Francis Alfred Francis - 4 months ago 15
JSON Question

How to parse Json using Java?

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

Answer

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.