I am trying to iterate over a json object using json simple. I have seen answers where you can do a getJSONObject("child")
from
{ "child": { "something": "value", "something2": "value" } }
But what if I just have something
{ "k1":"v1", "k2":"v2", "k3":"v3" }
And want to iterate over that json
object. This:
Iterator iter = jObj.keys();
Throws:
cannot find symbol symbol : method keys() location: class org.json.simple.JSONObject
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
simple package contains important classes like JSONValue, JSONObject, JSONArray, JsonString and JsonNumber. We need to install the json-simple. jar file to execute a JSON program whereas org. json library has classes to parse JSON for Java.
Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:
JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader("simple.json")); JSONObject jsonObject = (JSONObject) obj; for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); System.out.println(jsonObject.get(key)); }
You can do like this
String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }"; JSONObject resobj = new JSONObject(jsonstring); Iterator<?> keys = resobj.keys().iterator(); while(keys.hasNext() ) { String key = (String)keys.next(); if ( resobj.get(key) instanceof JSONObject ) { JSONObject xx = new JSONObject(resobj.get(key).toString()); Log.d("res1",xx.getString("something")); Log.d("res2",xx.getString("something2")); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With