当我从服务器获取JSON字符串时,JSONArray不起作用

时间:2012-11-01 02:59:40

标签: java android json

我已经找到了一些答案,但我不确定为什么我的确失败......

代码看起来像这样

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String json = EntityUtils.toString(httpEntity);

        //Convert to JsonArray
        JSONArray jsonArray = new JSONArray(json);

        Log.i(DEBUG_TAG, Integer.toString(jsonArray.length()));

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Log.i(DEBUG_TAG, jsonObject.getString(KEY_ID));

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            // adding each child node to HashMap key => value
            map.put(KEY_ID, jsonObject.getString(KEY_ID));
            map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
            map.put(KEY_ARTIST, jsonObject.getString(KEY_ARTIST));
            map.put(KEY_DURATION, jsonObject.getString(KEY_DURATION));
            map.put(KEY_VOTECOUNT, jsonObject.getString(KEY_VOTECOUNT));
            map.put(KEY_THUMB_URL, jsonObject.getString(KEY_THUMB_URL));
            map.put(KEY_GENRE, jsonObject.getString(KEY_GENRE));

            //Adding map to ArrayList
            if (Integer.parseInt(jsonObject.getString(KEY_VOTECOUNT)) == -1){
                //If VoteCount is -1 then add to header
                headerList.add(map);
            }else {
                songsList.add(map);
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

当我在String json上运行logcat时,它似乎显示正确的信息,就像这样......

  {
"userdata": [
    {
        "id": "8",
        "title": "Baby One More Time",
        "artist": "Britney Spears",
        "duration": "03:24:00",
        "votes": "0",
        "thumb_url": "http://api.androidhive.info/music/images/dido.png",
        "genre": null
    },
    {
        "id": "2",
        "title": "As Long As You Love Me",
        "artist": "Justin Bieber",
        "duration": "05:26:00",
        "votes": "0",
        "thumb_url": "http://api.androidhive.info/music/images/enrique.png",
        "genre": "Rock"
    }
]
}

和logcat on

JSONArray jsonArray = new JSONArray(json);

告诉我jsonArray.length()

  

10-31 22:57:28.433:W / CustomizedListView(26945):错误!索引无效   0,大小为0

请告诉我

谢谢,

4 个答案:

答案 0 :(得分:2)

问题是它不是JSON数组。它是一个JSON对象,JSON数组以[以#结尾]

开头

enter image description here

和JSON对象以{并以}结尾

开头

enter image description here

进一步参考,你可以在这里看到它 - &gt; http://www.json.org/

修复它你应该首先将你的json字符串转换为json对象,然后解析json对象以获取json数组

这是从jsonobject

解析json数组的一个例子
void ParseAPIWithJSON()
    {
     String readGooglePlace = readGooglePlaceAPI();
     try
     {

      InputStream is = new ByteArrayInputStream(readTwitterFeed.getBytes("UTF-8"));
      byte [] buffer = new byte[is.available()];
      while (is.read(buffer) != -1);
      String jsontext = new String(buffer);
      JSONObject entries = new JSONObject(jsontext);

      JSONArray hasil = entries.getJSONArray("results");
      results = hasil.getString(o);
      Log.i("TAG", results);
      int i;
      Log.i("TAG", Integer.toString(hasil.length()));
      numberofPlaces = hasil.length();
      for (i=0;i<hasil.length();i++)
      {
       JSONObject data = hasil.getJSONObject(i);
       namePlaces[i] = data.getString("name");
       Log.i("TAG", namePlaces[i]);
       JSONObject geometry = data.getJSONObject("geometry");
       JSONObject location = geometry.getJSONObject("location");
       latPlaces[i] = location.getDouble("lat");
       longPlaces[i] = location.getDouble("lng");
       Log.i("TAG", "Lat : "+latPlaces[i]+" Long : "+longPlaces[i]);
         }

     }
     catch (Exception je)
     {
      Log.e("TEST1", je.getMessage());
     }
    }

从整个代码中我认为你只需要理解这个

 String jsontext = new String(buffer);
 JSONObject entries = new JSONObject(jsontext);
 JSONArray hasil = entries.getJSONArray("results");

convert string-&gt; jsonobject-&gt; jsonarray-&gt; get value

答案 1 :(得分:0)

您需要替换:

JSONArray jsonArray = new JSONArray(json);

JSONArray jsonArray = new JSONObject(json).getJSONArray("userdata");

答案 2 :(得分:0)

在你的情况下,JSON是从jsonobject而不是jsonArray开始的,所以首先你要声明jsonobject而不是jsonarray。

 try {

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = jsonObject.getJSONArray("userdata");


        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonUserdata = jsonArray.getJSONObject(i);


            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            // adding each child node to HashMap key => value
            map.put(KEY_ID, jsonUserdata.getString(KEY_ID));
            map.put(KEY_TITLE, jsonUserdata.getString(KEY_TITLE));
            map.put(KEY_ARTIST, jsonUserdata.getString(KEY_ARTIST));
            map.put(KEY_DURATION, jsonUserdata.getString(KEY_DURATION));
            map.put(KEY_VOTECOUNT, jsonUserdata.getString(KEY_VOTECOUNT));
            map.put(KEY_THUMB_URL, jsonUserdata.getString(KEY_THUMB_URL));
            map.put(KEY_GENRE, jsonUserdata.getString(KEY_GENRE));


        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

有关更多信息,请使用链接:

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

答案 3 :(得分:0)

试试这个。

            HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    String response_string;

    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity httpEntity = response.getEntity();

        InputStream is = httpEntity.getContent();
        InputStreamReader isr = new InputStreamReader(is);

        char[] arr = new char[8*1024]; // 8K at a time
        StringBuffer buf = new StringBuffer();;
        int numChars;


        while ((numChars = isr.read(arr,0,arr.length))>0)
        {
            buf.append(arr,0,numChars);
        }

        response_string = buf.toString();

    } 
    catch (ClientProtocolException e) 
    {
        response_string = "Network Error : " + e.getMessage();
        e.printStackTrace();
    } 
    catch (IOException e) 
    {
        response_string = "Network Error : " + e.getMessage();
        e.printStackTrace();
    }
    catch(Exception e)
    {
        response_string = "Network Error : " + e.getMessage();
        e.printStackTrace();
    }

 JSONArray jsonArray = new JSONArray(response_string);