json數據格式已經是互聯網數據通信的標準格式了,各種後端語言都支持json數據的處理,重要的是json格式具有輕便,靈活,語言清晰特點,android也完美的實現對json數據格式的解析;安卓下面對json數據格式解析有兩種,JSONObject類實現和谷歌提供的Gson解析;這裏以官方JSONObject來說明
現在項目assets目錄下新建一個json文件,test.json
{
"languages":[
{"id":1,"ide":"Eclipse","name":"java"},
{"id":2,"ide":"PhpStorm","name":"php"},
{"id":3,"ide":"Visual Studio","name":"asp.net"}
],
"cat":"it"
}
回到MainActivity當中實現
package com.example.testjson;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"),"UTF-8");
BufferedReader br =new BufferedReader(isr);
StringBuilder sb =new StringBuilder();
String line="";
while((line=br.readLine())!=null){
sb.append(line);
}
try {
JSONObject root =new JSONObject(sb.toString());
String cat =root.getString("cat");
System.out.println("cat鍵結果是:"+cat);
JSONArray arr= root.getJSONArray("languages");
for(int i=0;i<arr.length();i++){
JSONObject obj =arr.getJSONObject(i);
System.out.println("第個"+i+"對象,屬性爲:"+"id="+obj.getInt("id")+",ide="+obj.getString("ide")+",name="+obj.getString("name"));
}
JSONArray jarray = new JSONArray();
JSONObject newobj =new JSONObject();
JSONObject obj1 =new JSONObject();
obj1.put("company", "韻達");
obj1.put("praise", "很垃圾");
obj1.put("star", 0);
JSONObject obj2 =new JSONObject();
obj2.put("company", "圓通");
obj2.put("praise", "一般");
obj2.put("star", 3);
JSONObject obj3 =new JSONObject();
obj3.put("company", "順豐");
obj3.put("praise", "速度很快!");
obj3.put("star", 5);
jarray.put(obj1);
jarray.put(obj2);
jarray.put(obj3);
newobj.put("wuliu", jarray);
newobj.put("theme", "物流");
System.out.println("新構造的json對象爲:"+newobj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}