2013-06-27 84 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(); 
    }