Reputation: 451
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 ??
Upvotes: 3
Views: 290
Reputation: 7988
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.
Upvotes: 4
Reputation: 42597
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.
Upvotes: 4