2011-06-15 73 views
2

好吧,我已經通過了大量關於PARSing JSON結果的示例,但沒有運氣。我有下面的JSON示例,我現在不想要狀態信息或geoLocation。我只想使用工作站對象,並從數組中選擇一些東西作爲列表顯示在我的ListView中。我不明白那裏的任何文件。PARSING JSON到ListView

有人能夠提供一個關於如何讀取JSON並將其放入ListView的簡單示例。這將非常有幫助。我沒有編寫任何代碼,因爲它們都不適合我。

{ 
"status": { 
    "error": "NO", 
    "code": 200, 
    "description": "none", 
    "message": "Request ok" 
}, 
"geoLocation": { 
    "city_id": "147", 
    "city_long": "Saint-Laurent", 
    "region_short": "QC", 
    "region_long": "Quebec", 
    "country_long": "Canada", 
    "country_id": "43", 
    "region_id": "35" 
}, 
"stations": [ 
    { 
     "country": "Canada", 
     "reg_price": "N\/A", 
     "mid_price": "N\/A", 
     "pre_price": "N\/A", 
     "diesel_price": "N\/A", 
     "address": "3885, Boulevard de la C\u00f4te-Vertu", 
     "diesel": "0", 
     "id": "33862", 
     "lat": "45.492367", 
     "lng": "-73.710915", 
     "station": "Shell", 
     "logo": "http:\/\/www.mygasfeed.com\/img\/station-logo\/logo-shell.png", 
     "region": "Quebec", 
     "city": "Saint-Laurent", 
     "reg_date": "N\/A", 
     "mid_date": "N\/A", 
     "pre_date": "N\/A", 
     "diesel_date": "N\/A", 
     "distance": "1.9km" 
    } 
] 
+0

我知道這是舊的,但如果任何人正在尋找一個教程來解析JSON到自定義ListView這裏是一個教程:http://ecetechprojects.wordpress.com/2014/02/26/android-complete-json-to-listview-tutorial/ – 2014-02-26 21:38:12

回答

3

這裏,你會如何解析陣列和列表視圖顯示它的一個例子。我不包括XML,但它是非常簡單的描述包含了國家和地址(或其他)的TXT字段列表視圖和多行結果:

String[] from = new String[] {"row_1", "row_2"}; 
int[] to = new int[] { R.id.country, R.id.address}; 
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>(); 

try { 
    JSONObject obj = new JSONObject(jsonString); 
    JSONArray stations = obj.getJSONArray("stations"); 
    Log.i(TAG,"Number of entries " + stations.length()); 
    for (int j = 0; j < stations.length(); j++) { 
      JSONObject jsonObject = stations.getJSONObject(j); 
      HashMap<String, String> map = new HashMap<String, String>(); 
      map.put("row_1", jsonObject.getString("country")); 
      map.put("row_2", jsonObject.getString("address")); 

      fillMaps.add(map); 
    } 
} catch (Exception e) { 
     e.printStackTrace(); 
} 

SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to); 
mListView.setAdapter(adapter); 
6

首先解析您的JSON對象,像這樣:

String str_json = "your json string"; 
try { 
    JSONObject obj = new JSONObject(str_json); 
    JSONArray stations = obj.getJSONArray("stations"); 
    //etc etc... 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 

然後解析這個JSONArray到定製站的ArrayList對象,您已經創建,例如:

public class Station { 

    public String country; 
    public int reg_price; 
    // etc etc... 
} 

4:24項目JSONArray放入ArrayList中:

ArrayList<Station> stationsArrList = new ArrayList<Station>(); 

int len = stations.size();  
for (int i = 0; i < len; i++){ 
    JSONObject stationObj = stations.getJSONObject(i); 
    Station station = new Station(); 

    for (int j = 0; j < stationObj.len(); j++){ 
     //add items from stationObj to station 
    } 
    stationsArrList.add(station); 
} 

然後創建一個適配器(假設你想要的信息的兩件以上顯示):

public class StationListAdapter extends BaseAdapter { 
    private static ArrayList<Station> stationArrayList; 

    private LayoutInflater inflator; 

    public StationListAdapter(Context context, ArrayList<Station> results) { 
     stationArrayList = results; 
     inflator = LayoutInflater.from(context); 
    } 

    public int getCount() { 
     if (stationArrayList == null) 
      return 0; 
     else 
      return stationArrayList.size(); 
    } 

    public Object getItem(int position) { 
     try { 
      return stationArrayList.get(position); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } 
    } 

    public long getItemId(int position) { 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = inflator.inflate(R.layout.list_item_station, null); 
      holder = new ViewHolder(); 
      holder.country = (TextView) convertView.findViewById(R.id.station_listview_item_one); 
      holder.reg_price = (TextView) convertView.findViewById(R.id.station_listview_item_two); 
      convertView.setTag(holder); 
     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 

     holder.country.setText(stationArrayList.get(position).getCountry()); 
     holder.reg_price.setText(stationArrayList.get(position).getRegPrice()); 

     return convertView; 
    } 

    static class ViewHolder { 
     TextView country; 
     TextView reg_price; 
     //etc 
    } 
} 

的調節器,你會使用你會爲每個列表的行定義列表視圖XML佈局。

最後,你得到的參考名單,並添加上的主要活動代碼數據:

stationList = (ListView) findViewById(R.id.station_list_view); 
stationListAdapter = new StationListAdapter(this, stationsArrList); 
stationList.setAdapter(stationListAdapter); 
+0

我是使用上面的示例,但獲取方法size()對於類型JSONArray&未定義方法len()對於JSONObject類型未定義。 Eclipse爲我提供了添加'cast'的選項,或者在'len'的情況下將其重命名爲'length'。有什麼想法嗎 ? TIA – 2013-05-06 11:45:57

+0

ArrayList dataitemArrList = new ArrayList (); \t int len = dataitems.size(); (i = 0; i 2013-05-06 11:48:51

+0

對不起,我忍不住 - 我剛纔做了這個答案,沒有一個好的設置來測試它。它當時確實有效。 – 2013-05-06 18:55:44

0
public class JSONParsingExampleActivity extends Activity { 
/** Called when the activity is first created. */ 

private ArrayList<String> id; 
private ArrayList<String> name; 
private ArrayList<String> email; 
private ArrayList<String> address; 
private ArrayList<String> gender; 
private ArrayList<String> mobile; 
private ArrayList<String> home; 
private ArrayList<String> office; 
ListView view; 
ProgressDialog mDialog=null;  // Thread code 
private Runnable viewOrders; // Thread code 
private Thread thread1; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    id=new ArrayList<String>(); 
    name=new ArrayList<String>(); 
    email=new ArrayList<String>(); 
    address=new ArrayList<String>(); 
    gender=new ArrayList<String>(); 
    mobile=new ArrayList<String>(); 
    home=new ArrayList<String>(); 
    office=new ArrayList<String>(); 
    view = (ListView)findViewById(R.id.listview); 
    mDialog=new ProgressDialog(this); // Thread code 
    mDialog.setMessage("Loading...."); 


    viewOrders =new Runnable() // Thread code 
    { 
     public void run()  // Thread code 
     { 
      Json_function(); 
      runOnUiThread(returnRes); 
     } 
    }; 
    thread1=new Thread(null,viewOrders,"Bacground"); 
    thread1.start(); 
    mDialog.show(); 
} 

private Runnable returnRes=new Runnable() // Thread code 
{ 

    @Override 
    public void run() // Thread code 
    { 
    mDialog.cancel(); 

     for(int i=0;i<id.size();i++) 
     { 
      System.out.println("=========================="); 
      System.out.println("id : - " +id.get(i)); 
      System.out.println("name : - " +name.get(i)); 
      System.out.println("email : - " +email.get(i)); 
      System.out.println("address : - " +address.get(i)); 
      System.out.println("gender : - " +gender.get(i)); 
      System.out.println("mobile : - " +mobile.get(i)); 
      System.out.println("home : - " +home.get(i)); 
      System.out.println("office : - " +office.get(i)); 
     } 

     ArrayAdapter<String> adapter= new ArrayAdapter<String>(JSONParsingExampleActivity.this, android.R.layout.simple_list_item_1, name); 

     view.setAdapter(new CustomAdapter(JSONParsingExampleActivity.this));   
    }  
}; 

private void Json_function() 
{ 
    String result=null; 

    try 
    { 
     result=getDataFromWebService("http://api.androidhive.info/contacts/"); 
     System.out.println("length old--> " +result); 
    } 
    catch(Exception e) 
    { 

    } 
    try 
    { 
     JSONObject json_data=new JSONObject(result); 
     JSONArray json_array=json_data.getJSONArray("contacts"); 
     System.out.println("json array length : - " +json_array.length()); 

     for(int i=0;i<json_array.length();i++) 
     { 
      json_data=json_array.getJSONObject(i); 

      id.add(json_data.getString("id")); 
      name.add(json_data.getString("name")); 
      email.add(json_data.getString("email")); 
      address.add(json_data.getString("address")); 
      gender.add(json_data.getString("gender")); 

      String str= json_data.getString("phone"); 
      JSONObject json_data1 = new JSONObject(str); 

      mobile.add(json_data1.getString("mobile")); 
      home.add(json_data1.getString("home")); 
      office.add(json_data1.getString("office")); 
     } 
    } 
    catch(Exception e1) 
    { 
     e1.printStackTrace(); 
    } 
} 

public static String getDataFromWebService(String strUrl) 
{ 
    StringBuffer strBuffer=new StringBuffer(); 
    InputStream is=null; 

    try 
    { 
     System.out.println("getdata from web service url:--> " +strUrl); 

     HttpClient httpclient=new DefaultHttpClient(); 
     HttpPost httppost=new HttpPost(strUrl); 

     HttpResponse httpresponse=httpclient.execute(httppost); 
     HttpEntity httpentity=httpresponse.getEntity(); 

     is=httpentity.getContent(); 

     int in=httpresponse.getStatusLine().getStatusCode(); 
     System.out.println("Response code:--> " +in); 
    } 
    catch(Exception e) 
    { 
     Log.e("log_tag", "Eroor in http connection" +e.toString()); 
    } 
    try 
    { 
     int ch; 

     while((ch=is.read())!=-1) 
      strBuffer.append((char)ch); 

     is.close(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return strBuffer.toString(); 
} 

    public class CustomAdapter extends BaseAdapter { 
    private Context mContext; 
    Application app; 
    private LayoutInflater inflater=null; 

    public CustomAdapter(Context c) { 
     mContext = c; 
     inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    public int getCount() { 
     return id.size(); 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    // create a new ImageView for each item referenced by the Adapter 
    public View getView(int position, View convertView, ViewGroup parent) { 

     View vi=convertView; 
     if (convertView == null)   
      vi = inflater.inflate(R.layout.list, null); 


     TextView txt=(TextView)vi.findViewById(R.id.txtview_id); 
     TextView txt1=(TextView)vi.findViewById(R.id.txtview_name); 
     TextView txt2=(TextView)vi.findViewById(R.id.txtview_email); 
     TextView txt3=(TextView)vi.findViewById(R.id.txtview_address); 
     TextView txt4=(TextView)vi.findViewById(R.id.txtview_gender); 
     TextView txt5=(TextView)vi.findViewById(R.id.txtview_mobile); 
     TextView txt6=(TextView)vi.findViewById(R.id.txtview_home); 
     TextView txt7=(TextView)vi.findViewById(R.id.txtview_office); 

     txt.setText("Id : " + id.get(position)); 
     txt1.setText("Name : " + name.get(position)); 
     txt2.setText("Email : " + email.get(position)); 
     txt3.setText("Address : " + address.get(position)); 
     txt4.setText("Gender : " + gender.get(position)); 
     txt5.setText("Mobile : " + mobile.get(position)); 
     txt6.setText("Home : " + home.get(position)); 
     txt7.setText("Office : " + office.get(position)); 

     return vi; 
    }; 
} 
}