2013-06-27 54 views
1

如何查看此Json结构并存储每个元素id名称链接picutre nb_album nb_fan radio,键入到列表中。这是我的json文件。Json Parser返回大小= 0 Android

{ 
     "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 
    } 

回答

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(); 
    }