01
package com.practice.json;
02
03
import org.json.JSONArray;
04
import org.json.JSONException;
05
import org.json.JSONObject;
06
07
import android.app.Activity;
08
import android.os.Bundle;
09
import android.util.Log;
10
11
public class JsonDemo extends Activity {
12
/*
13
* 解析JSON的例子,str保存的是JSON代码,解析后的数据在LogCat里输出
14
*/
15
16
String TAG = "Json message";
17
18
@Override
19
public void onCreate(Bundle savedInstanceState) {
20
super.onCreate(savedInstanceState);
21
setContentView(R.layout.main);
22
detectJSON();
23
}
24
25
private void detectJSON() {
26
String str = "{"+
27
28
"\"日期\" : \"2011-06-06\","+
29
30
//Like 是 JSONObject
31
"\"Like\" : {"+
32
"\"Name\" : \"加内特\","+
33
"\"Height\" : \"2.11cm\","+
34
"\"Age\" : 35"+
35
"},"+
36
37
//LikeList 就是一个 JSONObject
38
"\"LikeList\":" +
39
"{\"List\": " +
40
"["+
41
//这里也是JSONObject
42
"{"+
43
"\"Name\" : \"Rose\","+
44
"\"Height\" : \"190cm\","+
45
"\"Age\" : 23"+
46
"},"+
47
//这里也是JSONObject
48
"{"+
49
"\"Name\" : \"科比\","+
50
"\"Height\" : \"198cm\","+
51
"\"Age\" : 33"+
52
"}"+
53
"]"+
54
"}"+
55
"}";
56
57
try {
58
JSONObject dataJson = new JSONObject(str);
59
Log.d(TAG, dataJson.getString("日期"));
60
61
JSONObject nbaJson = dataJson.getJSONObject("Like");
62
63
Log.d(TAG, nbaJson.getString("Name"));
64
Log.d(TAG, nbaJson.getString("Height"));
65
Log.d(TAG, nbaJson.get("Age").toString());
66
67
JSONObject listJson = dataJson.getJSONObject("LikeList");
68
JSONArray arrayJson = listJson.getJSONArray("List");
69
70
for(int i=0;i<arrayJson.length();i++) {
71
72
JSONObject tempJson = arrayJson.optJSONObject(i);
73
74
Log.d(TAG, tempJson.getString("Name"));
75
Log.d(TAG, tempJson.getString("Height"));
76
Log.d(TAG, tempJson.getString("Age").toString());
77
}
78
79
80
} catch (JSONException e) {
81
System.out.println("Something wrong...");
82
e.printStackTrace();
83
}
84
}
85
}