Alfred Francis Alfred Francis - 1 year ago 81
JSON Question

How to parse Json using Java?

I want to parse a json object in java.The json file is


i am trying to write a java program to print above json as


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){
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++){
}catch (Exception e) {
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 Source

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();

        String key = (String);
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download