Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Json using Java?

Tags:

java

json

arrays

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

like image 605
Alfred Francis Avatar asked Sep 19 '26 15:09

Alfred Francis


1 Answers

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.

like image 123
udalmik Avatar answered Sep 21 '26 05:09

udalmik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!