今天學習了一下解析json的知識,把我學習的的一個小例子拿出來和大家分享一下
下面是代碼:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String x;
JSONObject obj;
try {
InputStream is = this.getResources().openRawResource(R.raw.json);
byte [] buffer = new byte[is.available()] ;
is.read(buffer);
TextView v = new TextView(this);
String json = new String(buffer,"utf-8");
obj = new JSONObject(json);
x = obj.getString("名稱");
Log.d("======名稱========",x);
x = obj.getString("網址");
Log.d("======網址========",x);
x = obj.getString("摘要");
Log.d("======摘要========",x);
JSONObject obj1 = obj.getJSONObject("網址資料");
x = obj1.getString("綜合");
Log.d("======綜合========",x);
x = obj1.getString("層級");
Log.d("======層級========",x);
x = obj1.getString("數量");
Log.d("======數量========",x);
JSONArray array = obj1.getJSONArray("綜合");
obj = array.getJSONObject(0);
x = obj.getString("綜合1");
Log.d("======綜合1========",x);
obj = array.getJSONObject(1);
x = obj.getString("綜合2");
Log.d("======綜合2========",x);
JSONStringer s = new JSONStringer();
Log.d("======================",s.object().key("a").value("aaa").endObject().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json檔案:
{
"名稱":"400電話 ",
"網址":"http://www.my400800.cn ",
"摘要":"",
"網址資料":
{
"數量":"60",
"層級":"61",
"單位":"62",
"綜合":
[
{
"綜合1":"100"
},
{
"綜合2":"110"
}
]
}
}