經過上幾章的學習,相信同學們對XML解析已經得心應手瞭,但今天我們要解析Json數據,因為Json數據占用數據量小,因此在Android中主要數據通信還是以Json為主,而且Json數據可以跟Android進行AJAX互動,相當方便哦,好瞭,不多說瞭,看圖跟代碼:
先上圖:
首先定義瞭Json數據:
{ "persons": [
{ "id": "1", "status":"大徙弟", "name": "孫悟空", "tool": "金箍棒", "number": "殺死瞭50隻妖怪" },
{ "id": "2", "status":"二徙弟", "name": "豬八戒", "tool": "九齒釘耙", "number": "殺死瞭43隻妖怪" },
{ "id": "3", "status":"三徙弟", "name": "沙和尚", "tool": "降妖寶杖", "number": "殺死瞭33隻妖怪" }
]}
接下來就是定義javaBean瞭,對於java開發來說,javaBean可以很方便地存儲和管理數據
public class Person
{
private String id;
private String status;
private String name;
private String tool;
private String number;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getTool()
{
return tool; www.aiwalls.com
}
public void setTool(String tool)
{
this.tool = tool;
}
public String getNumber()
{
return number;
}
public void setNumber(String number)
{
this.number = number;
}
@Override
public String toString()
{
return "Person [id=" + id + ", status=" + status + ", name=" + name
+ ", tool=" + tool + ", number=" + number + "]";
}
}
接下來就是Json的處理瞭,定義瞭一個JsonHandler類
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonHandler
{
private InputStream input;
private List<Person> persons;
private Person person;
public JsonHandler()
{
}
public JsonHandler(InputStream input)
{
this.input = input;
}
public void setInput(InputStream input)
{
this.input = input;
}
public List<Person> getPersons()
{
persons = new ArrayList<Person>();
try
{
//自定義方法,從輸入流中取得字符串
String json_str = getJsonString(input);
//通過字符串生成Json對象
JSONObject object = new JSONObject(json_str);
//將Json對象中的persons數據轉換成Json數組
JSONArray array = object.getJSONArray("persons");
//數組長度
int length = array.length();
for (int i = 0; i < length; i++)
{
//將每一個數組再轉換成Json對象
JSONObject obj = array.getJSONObject(i);
person = new Person();
person.setId(obj.getString("id"));
person.setStatus(obj.getString("status"));
person.setName(obj.getString("name"));
person.setTool(obj.getString("tool"));
person.setNumber(obj.getString("number"));
persons.add(person);
}
return persons;
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 將輸入流中數據整合成字符串
*
* @param input
* 輸入流
* @return
* @throws Exception
*/
private String getJsonString(InputStream input) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder sb = new StringBuilder();
for (String s = reader.readLine(); s != null; s = reader.readLine())
{
sb.append(s);
}
return sb.toString();
}
}
OK,到這裡數據應該能解析出來瞭,可以通過測試類來測試一下,呵呵,我還是比較喜歡邊測試邊做下一步開發
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import android.os.Environment;
import android.test.AndroidTestCase;
public class HandlerTest extends AndroidTestCase
{
public void testJsonGetPersons()
{
// 取得當前SD目錄下的文件路徑
File SD_Files = Environment.getExternalStorageDirectory();
// 取得persons.xml文件的路徑,這裡我是存在sdcard/data.json
String file_path = SD_Files.getName() + File.separator + "data.json";
try
{
FileInputStream fis = new FileInputStream(new File(file_path));
JsonHandler jsonHandler = new JsonHandler(fis);
List<Person> persons = jsonHandler.getPersons();
System.out.println(persons);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
好,測試沒問題瞭,那我們就上主Activity類瞭
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class JsonActivity extends Activity
{
private ListView listView;
private SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_handler);
listView = (ListView) findViewById(R.id.xml_list);
try
{
// 自完義適配方法
getAdapter();
} catch (Exception e)
{
e.printStackTrace();
}
listView.setAdapter(adapter);
}
private void getAdapter() throws Exception
{
List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
//取得SD卡目錄
File SD_Files = Environment.getExternalStorageDirectory();
//取得文件路徑
String file_path = SD_Files.getName() + File.separator + "data.json";
//Json處理
FileInputStream fis = new FileInputStream(new File(file_path));
JsonHandler jsonHandler = new JsonHandler(fis);
List<Person> persons = jsonHandler.getPersons();
// 將persons中的數據轉換到ArrayList<Map<String,String>>中
// String>>中,因為SimpleAdapter要用這個類型的數據進行適配
Map<String, String> map;
for (Person p : persons)
{
map = new HashMap<String, String>();
map.put("id", p.getId());
map.put("status", p.getStatus());
map.put("name", p.getName());
map.put("tool", p.getTool());
map.put("number", p.getNumber());
lists.add(map);
}
// HashMap<String, String>中的key
String[] from = { "id", "status", "name", "tool", "number" };
// list_item.xml中對應的控件ID
int[] to = { R.id.item_id, R.id.item_status, R.id.item_name,
R.id.item_tool, R.id.item_number };
adapter = new SimpleAdapter(this, lists, R.layout.handler_list_item,
from, to);
}
}
這裡面還定義瞭幾個Layout,也一起送上吧:
xml_handler.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content" android:text="唐僧的三個徙弟"
android:layout_height="wrap_content" android:id="@+id/textView1"
android:paddingLeft="10dip" android:paddingBottom="10dip"></TextView>
<ListView android:id="@+id/xml_list" android:layout_height="wrap_content"
android:layout_width="match_parent"></ListView>
</LinearLayout>
handler_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="10dip"
android:paddingRight="10dip">
<LinearLayout android:id="@+id/linearLayout1"
android:layout_height="wrap_content" android:layout_width="match_parent">
<TextView android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content" android:text="TextView"
android:layout_height="wrap_content" android:id="@+id/item_id" android:paddingRight="30dip"></TextView>
<TextView android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content" android:text="TextView"
android:layout_height="wrap_content" android:id="@+id/item_status" android:paddingRight="30dip"></TextView>
<TextView android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content" android:text="TextView"
android:layout_height="wrap_content" android:id="@+id/item_name"></TextView>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout2"
android:layout_height="wrap_content" android:layout_width="match_parent">
<TextView android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content" android:text="TextView"
android:layout_height="wrap_content" android:id="@+id/item_tool" android:paddingRight="30dip"></TextView>
<TextView android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content" android:text="TextView"
android:layout_height="wrap_content" android:id="@+id/item_number"></TextView>
</LinearLayout>
</LinearLayout>
好瞭,Json的數據處理我們也學習完瞭.
因為找不到比較好的文件服務器,如果哪位同學想要源碼的,可以留郵件地址,謝謝
摘自:kangkangz4的專欄