在android中显示json数据时出错查找错误
在第三个log.d(“Lee”,“working”)之后显示错误org.json.JSONException和org.json.typemismatch以及org.json.getJSONObject 这是用于将json数据转换为android的格式正确的列表视图的代码在android中显示json数据时出错查找错误,json,Json,在第三个log.d(“Lee”,“working”)之后显示错误org.json.JSONException和org.json.typemismatch以及org.json.getJSONObject 这是用于将json数据转换为android的格式正确的列表视图的代码 public class FlowerJSONParser { public static List<Flower> parserFeed(String content) { try {
public class FlowerJSONParser {
public static List<Flower> parserFeed(String content)
{
try
{
Log.d("Lee", "working");
JSONArray ar = new JSONArray(content);
Log.d("Lee", "working");
List<Flower> flowerList = new ArrayList<>();
for(int i=0; i< ar.length(); i++)
{
Log.d("Lee", "working");
JSONObject obj = ar.getJSONObject(i);
Log.d("Lee", "working");
Flower flower = new Flower();
Log.d("Lee", "working");
flower.setId(obj.getString("id"));
flower.setNotes(obj.getString("notes"));
flowerList.add(flower);
}
return flowerList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
公共类FlowerJSONParser{
公共静态列表parserFeed(字符串内容)
{
尝试
{
日志d(“李”,“工作”);
JSONArray ar=新JSONArray(内容);
日志d(“李”,“工作”);
List flowerList=新建ArrayList();
对于(int i=0;i
您正试图从JSONArray“ar”获取JSONObject。因此,必须确保数组中的所有元素都是JSONObject。若并没有,那个么在将元素转换为JSONObject的过程中一定会出现异常
请注意,JSONArray中的元素可以是任何主类型(int/long/boolean…),包装类(Integer/long/boolean…),字符串,JSONObject,甚至是另一个JSONArray。
因此,必须在ar.getJSONObject(i)之前确认元素的类型
另一个用法是:
将ar.getJSONObject(i)替换为ar.optJSONObject(i)。
通过这种方式,如果元素不是JSONObject,您将获得null而不是异常