以下是JSON链接
{
"AF": {
"country_name": "Afghanistan",
"dialling_code": "+93"
},
"AL": {
"country_name": "Albania",
"dialling_code": "+355"
},
"DZ": {
"country_name": "Algeria",
"dialling_code": "+213"
},
从上面的JSON链接我尝试使用下面的代码从JSON中检索数据。
try {
jsonObject = new JSONObject(JSON_STRING);
countryname = jsonObject.getString("country_name");
dialingcode = jsonObject.getString("dialling_code");
Log.d("COUNTRYNAME", countryname);
Log.d("DIALER_CODE", dialingcode);
} catch (JSONException e1) {
e1.printStackTrace();
}
答案 0 :(得分:0)
您可以从Keys
获取JSONObject
并重复密钥。下面是一个例子。
private void parse(String jsonString) {
try {
JSONObject resObject = new JSONObject(jsonString);
Iterator<String> iterator = resObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();// key can be used as Country code
JSONObject data = resObject.getJSONObject(key);
String country_name = data.getString("country_name");
String dialling_code = data.getString("dialling_code");
}
} catch (Exception e) {
}
}
答案 1 :(得分:0)
您可以将所有键提取到List或ArrayList中,然后循环此ArrayList以获取每个JSON键的详细信息。
jsonObject = new JSONObject(JSON_STRING);
Iterator keys= jsonObject .keys();
while(keys.hasNext()) {
String key = (String) keys.next();
JSONObject data = resObject.getJSONObject(key);
String country_name = data.getString("country_name");
String dialling_code = data.getString("dialling_code");
}
答案 2 :(得分:0)
试试这个
try {
JSONObject jsonObject = new JSONObject("your json response");
Iterator iteratorObj = jsonObject.keys();
while (iteratorObj.hasNext())
{
String JsonObjCountryCode = (String)iteratorObj.next();
Log.i("Country Code key", JsonObjCountryCode);
JSONObject jo_code = jsonObject.getJSONObject(JsonObjCountryCode);
Iterator<String> keys = jo_code.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jo_code.getString(key);
Log.i("country_name value", value);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}