Android開發中json數據的解釋是一個很常用的功能,今天來說一下json數據的解釋。我們用一個例子來說明一下。
首先我們新建一個工程json,然後準備一個json格式的文件放在assets目錄下面。這裏是 test.json:
{
"employees":[
{"id":1,"language":"java","ide":"eclipse_for_java"},
{"id":2,"language":"php","ide":"eclipse_for_php"}
],
"number":123
}
在onCreate方法裏面創建PraseJson方法:
private void PraseJson() {
try {
//將json數據寫入數據流
InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"),"utf-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder bulider = new StringBuilder();
while((line=br.readLine())!=null)
{
bulider.append(line);
}
br.close();
isr.close();
//至此,我們已經獲得了json數據的內容了
JSONObject jso = new JSONObject(bulider.toString());//獲取json對象
JSONArray jsa = jso.getJSONArray("employees");//獲取json數組
for(int i=0;i<jsa.length();i++)
{
JSONObject json = jsa.getJSONObject(i);//獲取json數組成員對象
//將json裏面的鍵值對數據打印輸出
System.out.println("id="+json.getInt("id"));
System.out.println("language="+json.getString("language"));
System.out.println("ide="+json.getString("ide"));
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
上面的註釋已經很清楚了,這是一段很簡單的代碼,最後,因爲解釋的過程用到io流和json,別忘記了捕捉一下異常。