Get json array keys in android

{ "204": { "host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/02\/0\/0\/A\/Content\/", "timestamp": 1385909880, "cover": ["17\/Pg017.png", "18\/Pg018.png", "1\/Pg001.png", "2\/Pg002.png"], "year": "2013", "month": "12", "day": "02", "issue": "2013-12-02", "id": "204" }, "203": { "host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/01\/0\/0\/A\/Content\/", "timestamp": 1385806902, "cover": ["1\/Pg001.png", "2\/Pg002.png", "3\/Pg003.png", "4\/Pg004.png"], "year": "2013", "month": "12", "day": "01", "issue": "2013-12-01", "id": "203" }, "202": { "host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/11\/30\/0\/0\/A\/Content\/", "timestamp": 1385720451, "cover": ["1\/Pg001.png", "2\/Pg002.png", "3\/Pg003.png", "4\/Pg004.png"], "year": "2013", "month": "11", "day": "30", "issue": "2013-11-30", "id": "202" } } 

The above sample json array, how to get 204, 203 and 202? Thanks

I tried:

 JSONArray issueArray = new JSONArray(jsonContent); for (int j = 0; j < issueArray.length(); j++) { JSONObject issue = issueArray.getJSONObject(j); String _pubKey = issue.getString(0); } 
+6
source share
4 answers

over json array sample how to get 204, 203 and 202?

No, the current line is JSONObject instead of JSONArray . you should get an Iterator using a JSONObject. keys () if the internal JSONObject keys are dynamic:

 JSONObject issueObj = new JSONObject(jsonContent); Iterator iterator = issueObj.keys(); while(iterator.hasNext()){ String key = (String)iterator.next(); JSONObject issue = issueObj.getJSONObject(key); // get id from issue String _pubKey = issue.optString("id"); } 
+21
source

The answer given by Mr. K is also right, but you can also use the jsonObject names () method. please find code example

 for(int i = 0; i<jsonobject.length(); i++){ Log.e(TAG, "Key = " + jsonobject.names().getString(i) + " value = " + jsonobject.get(jsonobject.names().getString(i))); } 

I hope this helps you.

+8
source

User this method for json dynamic iteration

 private void parseJson(JSONObject data) { if (data != null) { Iterator<String> it = data.keys(); while (it.hasNext()) { String key = it.next(); try { if (data.get(key) instanceof JSONArray) { JSONArray arry = data.getJSONArray(key); int size = arry.length(); for (int i = 0; i < size; i++) { parseJson(arry.getJSONObject(i)); } } else if (data.get(key) instanceof JSONObject) { parseJson(data.getJSONObject(key)); } else { System.out.println("" + key + " : " + data.optString(key)); } } catch (Throwable e) { System.out.println("" + key + " : " + data.optString(key)); e.printStackTrace(); } } } } 
+6
source

Here you are trying to get a JSONArray , but in the json answer it is JSONObject .

Use the following code.

 JSONObject issueObject = new JSONObject(jsonContent); String _pubKey = issueObject.getString(0); 
-1
source

Source: https://habr.com/ru/post/959145/


All Articles