Java Program to loop over JSONObject and print all properties
When you parse your JSON String utilizing JSONParser, you get a JSONObject, however its of no use if you’d like a POJO i.e. a plain outdated Java object. For instance, you probably have following JSON mesage which signify Efficient Java ebook, you ideall need a Java object representing identical information:
{ "title": "Efficient Java", "creator": "Joshua Bloch", "value": 42, "12 months": 2018, "version": 3, "rankings": 10 }
class EBook{ non-public String title; non-public String creator; non-public int value; non-public int 12 months; non-public int version; non-public int rankings .... }
Anyway, Right here is my pattern Java program to reveal how one can loop over a JSONObject to print all properties and their values.Â
public static void foremost(String args[]){ // Iterating over JSONOjbect to print all keys and values JSONParser parser = new JSONParser(); attempt { JSONObject json = (JSONObject) parser.parse(JSON); Set<String> keyset = json.keySet(); Iterator<String> keys = keyset.iterator(); whereas(keys.hasNext()){ String key = keys.subsequent(); Object worth = json.get(key); System.out.println( key +" : " + worth); } } catch (ParseException e) { e.printStackTrace(); } } }
We are able to iterate over this Set to retrieve all keys as proven beneath:
Iterator<String> keys = keyset.iterator(); whereas(keys.hasNext()){ String key = keys.subsequent(); Object worth = json.get(key); System.out.println( key +" : " + worth); }
Now, for those who want worth you’ll be able to simply name the JSONObject.get() or JSONObject.getOrDefault() methodology to get the worth. As soon as you bought each key and worth, you’ll be able to merely print them utilizing System.out.println() methodology. If you wish to create an object, you’ll be able to retailer these values to cross to the constructor, as I did in final instance.Â
That is all about learn how to iterate over JSONObject in Java to print all keys and values. It is similar to the way you iterate over a map to print all key-value pair. You simply want to recollect to incorporate the json-simple.jar in your classpath if you wish to course of your JSON Message like this.
Thanks for studying this text up to now. For those who like this Java JSON
tutorial utilizing json-simple library then please share it with your pals and
colleagues. When you’ve got any questions or suggestions then please drop a
be aware.Â