{
\"204\": {
\"host\": \"https:\\/\\/abc.com\\/production-source\\/ChangSha\\/2013\\/12\\/02\\/0\\/0\\/A\\/Content\\/\",
\"timestamp\": 138590988
Here you are trying to get JSONArray
but in json response it is JSONObject
.
Use following code.
JSONObject issueObject = new JSONObject(jsonContent);
String _pubKey = issueObject.getString(0);
User this method to iterate json dynamically
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();
}
}
}
}
above sample json array , how to get the 204, 203 and 202?
No, current String is JSONObject
instead of JSONArray
. you should get Iterator using JSONObject. keys () if inner JSONObject keys dynamic as:
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");
}
Answer given by Mr. K is also right but you can also use jsonObject names() method. please find the sample code
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 dis will help you
You can also use names()
as below to get the keys as JSONArray
:
JSONArray jArray = jsonObject.names();
int len = jsonObject.length();
for (int i=0; i<len; i++) {
String keyName = (String)jArray.get(i);
JSONObject jValue = jsonObject.getJSONObject(keyName);
String _pubKey = jValue.optString("id");
//get the other values from jValue
}