效果图:
Json数据;
{"data": {"info":[ {"id":"01","name":"张三","年龄":"22","地址":"成都"}, {"id":"02","name":"李四","年龄":"23","地址":"北京"}, {"id":"03","name":"王五","年龄":"24","地址":"西安"}, {"id":"04","name":"赵六","年龄":"25","地址":"上海"}, {"id":"05","name":"周七","年龄":"26","地址":"深圳"} ] } }
xml布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="43dp" > </ListView> </RelativeLayout>
java代码:
package com.example.wzf.app.demo.activity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.example.wzf.app.demo.R; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class JsonActivity extends Activity { ListView listView1; BufferedReader mBufferedReader; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.json); listView1 = (ListView) findViewById(R.id.listView1); String jsonString = getJson(); String[] json = bindDataToListView(jsonString); ArrayAdapter aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, json); listView1.setAdapter(aa); } private String[] bindDataToListView(String jsonString) { try { String[] ss = new String[5]; JSONObject jsonObject = new JSONObject(jsonString).getJSONObject("data"); JSONArray jsonArray = jsonObject.getJSONArray("info"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jo = (JSONObject) jsonArray.opt(i); ss[i] = jo.getInt("id") + " " + jo.getString("name")+ " " + jo.getString("年龄") + " " + jo.getString("地址"); } return ss; } catch (JSONException e) { e.printStackTrace(); } return null; } private String getJson() { StringBuilder builder = new StringBuilder(); try { InputStream in = getResources().getAssets().open("jsontext.json"); Reader reader = new InputStreamReader(in, "GBK"); mBufferedReader = new BufferedReader(reader); String value = ""; while ((value = mBufferedReader.readLine()) != null) { builder.append(value); } } catch (Exception e) { e.printStackTrace(); } finally { if (mBufferedReader != null) { try { mBufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return builder.toString(); } }