Json Parser返回size = 0 Android

时间:2013-06-27 06:30:41

标签: android

我如何看待这个Json结构并存储每个元素的id名称链接picutre nb_album nb_fan radio,输入到列表中。这是我的json文件。

 {
        "data": [
            {
                "id": "1214294",
                "name": "The Pop Rock Boys",
                "link": "http://www.deezer.com/artist/1214294",
                "picture": "https://api.deezer.com/2.0/artist/1214294/image",
                "nb_album": 7,
                "nb_fan": 3,
                "radio": false,
                "type": "artist"
            },
            {
                "id": "813196",
                "name": "Ringtone Pop Rock",
                "link": "http://www.deezer.com/artist/813196",
                "picture": "https://api.deezer.com/2.0/artist/813196/image",
                "nb_album": 0,
                "nb_fan": 4,
                "radio": false,
                "type": "artist"
            },
            {
                "id": "4165034",
                "name": "Rock of Pop",
                "link": "http://www.deezer.com/artist/4165034",
                "picture": "https://api.deezer.com/2.0/artist/4165034/image",
                "nb_album": 1,
                "nb_fan": 0,
                "radio": false,
                "type": "artist"
            },
            {
                "id": "4022223",
                "name": "instrumental / Pop / Rock",
                "link": "http://www.deezer.com/artist/4022223",
                "picture": "https://api.deezer.com/2.0/artist/4022223/image",
                "nb_album": 0,
                "nb_fan": 1,
                "radio": false,
                "type": "artist"
            }
        ],
        "total": 4
    }

1 个答案:

答案 0 :(得分:6)

您将初始字符串解析为数组。它不是一个数组,它的对象包含一个名为“data”的数组。您需要将其解析为JSONObject,然后从中获取名为data的数组,然后像您一样循环。

    try {
         JSONArray articlesArray = new JSONObject(jString).getJSONArray("data");
         JSONObject aObject;
         for(int i=0; i<articlesArray.length(); i++){
             aObject=articlesArray.getJSONObject(i);

             SearchTrack a=new SearchTrack();
             a.setId(aObject.getString("id"));
             a.setLink(aObject.getString("link"));
             a.setName(aObject.getString("name"));
             a.setPicture(aObject.getString("picture"));
             a.setNbAlbum(aObject.getString("nb_album"));
             a.setNbFan(aObject.getString("nb_fan"));
             a.setRadio(aObject.getString("radio"));
             a.setType(aObject.getString("type"));

             articles.add(a);
         }
     }catch (JSONException e) {
         e.printStackTrace();
     }