我有一个JSONObject,其值如下:
{
"Success": true,
"City": {
"1": "noida",
"2": "Delhi",
"3": "Kanpur",
"4": "Gurgaon",
"5": "Mumbai",
"7": "Noida",
"8": "NEWYORK",
"9": "Patna"
}
}
我有关于每个值的关键值,但没有关于键“6”的值。因此它返回“No value for 6”异常。我试图通过使用此代码删除它但失败了...请记住,城市将以String []的形式呈现在微调器中。
代码如下:
JSONObject jsonCities = jsonObject.getJSONObject("City");
int len = jsonCities.length();
Log.i("Length of jsonCities is :", ""+len);
for(int i=1;i<=len;i++)
{
if(jsonCities.get(""+i)==null)
{
Log.i("NULL VALUE", "NULL VALUE");
continue;
}
else
{
Log.i("Cities :",""+jsonCities.getString(""+i));
cities_hashmap.put(""+i, ""+jsonCities.getString(""+i));
Log.i("cities_hashmap", ""+cities_hashmap);
}
}
cities = new String[cities_hashmap.size()];
for(int j=1;j<=cities_hashmap.size();j++)
{
Log.i("CITY IS :", cities_hashmap.get(""+j));
cities[j-1] = cities_hashmap.get(""+j);
Log.i("City Array in String form is :", ""+cities);
}
context.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Registration.this, android.R.layout.simple_spinner_item, cities);
country.setAdapter(adapter);
}
});
答案 0 :(得分:0)
就这样使用:
String value = jsonCities.getString(Integer.toString(i));
答案 1 :(得分:0)
你可以使用JsonObject的has()方法找到密钥是否可用,如果找到密钥则返回true,返回false。
if(jsonCities.has(""+i)){
// do the thing
}
从此链接查看更多方法
答案 2 :(得分:0)
跳过 6 为
for(int i=1;i<=len;i++)
{
if(i == 6 )
{
i += 1;
}
if(jsonCities.get(""+i)==null)
{
Log.i("NULL VALUE", "NULL VALUE");
continue;
}
else
{
Log.i("Cities :",""+jsonCities.getString(""+i));
cities_hashmap.put(""+i, ""+jsonCities.getString(""+i));
Log.i("cities_hashmap", ""+cities_hashmap);
}
...
...
答案 3 :(得分:0)
您可以更改此'for'循环
for(int i=1;i<=len;i++)
与
Iterator it = jsonCities.keys();
while(it.hasNext())
{
String key = it.next().toString();
...
}