Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through JSONObject from root in json simple

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 
like image 454
Z2VvZ3Vp Avatar asked Jun 23 '14 17:06

Z2VvZ3Vp


People also ask

Can you iterate JSON object Java?

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.

What is the difference between org JSON JSON object and org JSON simple JSON object?

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.


2 Answers

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)); } 
like image 113
M A Avatar answered Sep 20 '22 19:09

M A


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"));     } } 
like image 30
Mojo Jojo Avatar answered Sep 20 '22 19:09

Mojo Jojo