Android使用JSON進行數據解析
一、Json數據格式的定義
Json的全稱:JavaScript Object Notation
Json建構於兩種結構:對象(“名稱/值”對的集合)和數組(值得有序列表)
1.Json對象是一個無序“名稱/值對”的集合。如: {“name”: “jack”, “age”:100}
2.數組是值得有序結合。如:{“students”:[{“name”: “jack”, “age”:100} ,{“name”: “tom”, “age”:10}]}
下面我們通過訪問一個JSON數據的網址連接來進行數據解析並在Android客戶端進行顯示(id、pinyin、name)
完成效果:
佈局文件:main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="NAME" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="PINYIN" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?android:attr/listDivider" />
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/pinyin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
HttpUtils類
public class HttpUtils {
public static String getJsonString(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
return changeInputStream(conn.getInputStream());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static String changeInputStream(InputStream inputStream) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String jsonString = "";
int len = 0;
byte[] data = new byte[1024];
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
jsonString = new String(outputStream.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
}
JsonTools類
public class JsonTools {
public static List<City> getListPersons(String key, String jsonString) {
List<City> list = new ArrayList<City>();
try {
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray(key);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
City city = new City();
city.setId(jsonObject.getInt("id"));
city.setName(jsonObject.getString("name"));
city.setPinyin(jsonObject.getString("pinyin"));
list.add(city);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
實體類City
public class City {
private String name;
private int id;
private String pinyin;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
@Override
public String toString() {
return "City [name=" + name + ", id=" + id + ", pinyin=" + pinyin + "]";
}
public City(String name, int id, String pinyin) {
super();
this.name = name;
this.id = id;
this.pinyin = pinyin;
}
public City() {
super();
}
}
MainActivity
public class MainActivity extends Activity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listview);
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
String path = "這裏填寫JSON數據的網址連接";
List<City> cities = JsonTools.getListPersons("cities",
HttpUtils.getJsonString(path));
for (City city : cities) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("ID", city.getId());
map.put("NAME", city.getName());
map.put("PINYIN", city.getPinyin());
data.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data,
R.layout.cell, new String[] { "ID", "NAME", "PINYIN" },
new int[] { R.id.id, R.id.name, R.id.pinyin });
listView.setAdapter(adapter);
}
}