大家好,今天给大家分享下Android解析Json的例子,我这里自己安装了Tomcat,让自己电脑充当下服务器,最重要的是,返回结果自己可以随便修改。
首先看下Json的定义,以及它和XML的比较:
JSON的定义:
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org
JSON Vs XML
1.JSON和XML的数据可读性基本相同
2.JSON和XML同样拥有丰富的解析手段
3.JSON相对于XML来讲,数据的体积小
4.JSON与JavaScript的交互更加方便
5.JSON对数据的描述性比XML较差
6.JSON的速度要远远快于XML.
Tomcat安装:
Tomcat下载地址http://tomcat.apache.org/ 下载后安装,如果成功,启动Tomcat,然后在浏览器里输入:http://localhost:8080/index.jsp,会有个Tomcat首页界面,
我们在Tomcat安装目录下webapps\ROOT下找到index.jsp,然后新建一个index2.jsp,用记事本或者什么的,编辑内容如下:
1 {students:[{name:'魏祝林',age:25},{name:'阿魏',age:26}],class:'三年二班'}
然后我们在浏览器里输入:http://localhost:8080/index2.jsp返回的结果如下(这就模拟出后台返回的数据了): 新建一个Android工程JsonDemo. 工程目录如下: 这里我封装了一个JSONUtil工具类,代码如下:
001 package com.tutor.jsondemo;
002 import java.io.IOException;
003 import java.io.InputStreamReader;
004 import java.io.UnsupportedEncodingException;
005 import org.apache.http.HttpEntity;
006 import org.apache.http.HttpResponse;
007 import org.apache.http.client.methods.HttpGet;
008 import org.apache.http.impl.client.DefaultHttpClient;
009 import org.apache.http.params.BasicHttpParams;
010 import org.apache.http.protocol.HTTP;
011 import org.json.JSONException;
012 import org.json.JSONObject;
013 import android.util.Log;
014 /**
015 * @author frankiewei.
016 * Json封装的工具类.
017 */
018 public class JSONUtil {
019 private static final String TAG = "JSONUtil";
020 /**
021 * 获取json内容
022 * @param url
023 * @return JSONArray
024 * @throws JSONException
025 * @throws ConnectionException
026 */
027 public static JSONObject getJSON(String url) throws JSONException, Exception {
028 return new JSONObject(getRequest(url));
029 }
030 /**
031 * 向api发送get请求,返回从后台取得的信息。
032 *
033 * @param url
034 * @return String
035 */
036 protected static String getRequest(String url) throws Exception {
037 return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
038 }
039 /**
040 * 向api发送get请求,返回从后台取得的信息。
041 *
042 * @param url
043 * @param client
044 * @return String
045 */
046 protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
047 String result = null;
048 int statusCode = 0;
049 HttpGet getMethod = new HttpGet(url);
050 Log.d(TAG, "do the getRequest,url="+url+"");
051 try {
052 //getMethod.setHeader("User-Agent", USER_AGENT);
053 HttpResponse httpResponse = client.execute(getMethod);
054 //statusCode == 200 正常
055 statusCode = httpResponse.getStatusLine().getStatusCode();
056 Log.d(TAG, "statuscode = "+statusCode);
057 //处理返回的httpResponse信息
058 result = retrieveInputStream(httpResponse.getEntity());
059 } catch (Exception e) {
060 Log.e(TAG, e.getMessage());
061 throw new Exception(e);
062 } finally {
063 getMethod.abort();
064 }
065 return result;
066 }
067 /**
068 * 处理httpResponse信息,返回String
069 *
070 * @param httpEntity
071 * @return String
072 */
073 protected static String retrieveInputStream(HttpEntity httpEntity) {
074 int length = (int) httpEntity.getContentLength();
075 //the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.
076 //length==-1,下面这句报错,println needs a message
077 if (length < 0) length = 10000;
078 StringBuffer stringBuffer = new StringBuffer(length);
079 try {
080 InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
081 char buffer[] = new char[length];
082 int count;
083 while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
084 stringBuffer.append(buffer, 0, count);
085 }
086 } catch (UnsupportedEncodingException e) {
087 Log.e(TAG, e.getMessage());
088 } catch (IllegalStateException e) {
089 Log.e(TAG, e.getMessage());
090 } catch (IOException e) {
091 Log.e(TAG, e.getMessage());
092 }
093 return stringBuffer.toString();
094 }
095 }
096 package com.tutor.jsondemo;
097 import java.io.IOException;
098 import java.io.InputStreamReader;
099 import java.io.UnsupportedEncodingException;
100 import org.apache.http.HttpEntity;
101 import org.apache.http.HttpResponse;
102 import org.apache.http.client.methods.HttpGet;
103 import org.apache.http.impl.client.DefaultHttpClient;
104 import org.apache.http.params.BasicHttpParams;
105 import org.apache.http.protocol.HTTP;
106 import org.json.JSONException;
107 import org.json.JSONObject;
108 import android.util.Log;
109 /**
110 * @author frankiewei.
111 * Json封装的工具类.
112 */
113 public class JSONUtil {
114
115 private static final String TAG = "JSONUtil";
116
117 /**
118 * 获取json内容
119 * @param url
120 * @return JSONArray
121 * @throws JSONException
122 * @throws ConnectionException
123 */
124 public static JSONObject getJSON(String url) throws JSONException, Exception {
125
126 return new JSONObject(getRequest(url));
127 }
128
129 /**
130 * 向api发送get请求,返回从后台取得的信息。
131 *
132 * @param url
133 * @return String
134 */
135 protected static String getRequest(String url) throws Exception {
136 return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
137 }
138
139 /**
140 * 向api发送get请求,返回从后台取得的信息。
141 *
142 * @param url
143 * @param client
144 * @return String
145 */
146 protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
147 String result = null;
148 int statusCode = 0;
149 HttpGet getMethod = new HttpGet(url);
150 Log.d(TAG, "do the getRequest,url="+url+"");
151 try {
152 //getMethod.setHeader("User-Agent", USER_AGENT);
153 HttpResponse httpResponse = client.execute(getMethod);
154 //statusCode == 200 正常
155 statusCode = httpResponse.getStatusLine().getStatusCode();
156 Log.d(TAG, "statuscode = "+statusCode);
157 //处理返回的httpResponse信息
158 result = retrieveInputStream(httpResponse.getEntity());
159 } catch (Exception e) {
160 Log.e(TAG, e.getMessage());
161 throw new Exception(e);
162 } finally {
163 getMethod.abort();
164 }
165 return result;
166 }
167
168 /**
169 * 处理httpResponse信息,返回String
170 *
171 * @param httpEntity
172 * @return String
173 */
174 protected static String retrieveInputStream(HttpEntity httpEntity) {
175
176 int length = (int) httpEntity.getContentLength();
177 //the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.
178 //length==-1,下面这句报错,println needs a message
179 if (length < 0) length = 10000;
180 StringBuffer stringBuffer = new StringBuffer(length);
181 try {
182 InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
183 char buffer[] = new char[length];
184 int count;
185 while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
186 stringBuffer.append(buffer, 0, count);
187 }
188 } catch (UnsupportedEncodingException e) {
189 Log.e(TAG, e.getMessage());
190 } catch (IllegalStateException e) {
191 Log.e(TAG, e.getMessage());
192 } catch (IOException e) {
193 Log.e(TAG, e.getMessage());
194 }
195 return stringBuffer.toString();
196 }
197 }
198
编写主Activity代码JSONDemoActivity,代码如下:
001 package com.tutor.jsondemo;
002 import org.json.JSONArray;
003 import org.json.JSONException;
004 import org.json.JSONObject;
005 import android.app.Activity;
006 import android.os.Bundle;
007 import android.widget.TextView;
008 public class JSONDemoActivity extends Activity {
009 /**
010 * 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2
011 */
012 private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp";
013 private TextView mStudentTextView;
014 private TextView mClassTextView;
015 @Override
016 public void onCreate(Bundle savedInstanceState) {
017 super.onCreate(savedInstanceState);
018 setContentView(R.layout.main);
019 setupViews();
020 }
021 /**
022 * 初始化
023 */
024 private void setupViews(){
025 mStudentTextView = (TextView)findViewById(R.id.student);
026 mClassTextView = (TextView)findViewById(R.id.classes);
027 try {
028 //获取后台返回的Json对象
029 JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL);
030 //获得学生数组
031 JSONArray mJsonArray = mJsonObject.getJSONArray("students");
032 //获取第一个学生
033 JSONObject firstStudent = mJsonArray.getJSONObject(0);
034 //获取班级
035 String classes = mJsonObject.getString("class");
036 String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生."
037 + "第一个学生姓名: " + firstStudent.getString("name")
038 + " 年龄: " + firstStudent.getInt("age");
039 mStudentTextView.setText(studentInfo);
040 mClassTextView.setText("班级: " + classes);
041 } catch (JSONException e) {
042 e.printStackTrace();
043 } catch (Exception e) {
044 e.printStackTrace();
045 }
046 }
047 }
048 package com.tutor.jsondemo;
049 import org.json.JSONArray;
050 import org.json.JSONException;
051 import org.json.JSONObject;
052 import android.app.Activity;
053 import android.os.Bundle;
054 import android.widget.TextView;
055 public class JSONDemoActivity extends Activity {
056 /**
057 * 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2
058 */
059 private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp";
060
061 private TextView mStudentTextView;
062
063 private TextView mClassTextView;
064
065
066 @Override
067 public void onCreate(Bundle savedInstanceState) {
068 super.onCreate(savedInstanceState);
069 setContentView(R.layout.main);
070 setupViews();
071 }
072 /**
073 * 初始化
074 */
075 private void setupViews(){
076 mStudentTextView = (TextView)findViewById(R.id.student);
077 mClassTextView = (TextView)findViewById(R.id.classes);
078
079 try {
080 //获取后台返回的Json对象
081 JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL);
082
083 //获得学生数组
084 JSONArray mJsonArray = mJsonObject.getJSONArray("students");
085 //获取第一个学生
086 JSONObject firstStudent = mJsonArray.getJSONObject(0);
087 //获取班级
088 String classes = mJsonObject.getString("class");
089
090
091
092 String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生."
093 + "第一个学生姓名: " + firstStudent.getString("name")
094 + " 年龄: " + firstStudent.getInt("age");
095
096 mStudentTextView.setText(studentInfo);
097
098 mClassTextView.setText("班级: " + classes);
099 } catch (JSONException e) {
100 e.printStackTrace();
101 } catch (Exception e) {
102 e.printStackTrace();
103 }
104 }
105 }
106
这里用到的布局文件main.xml代码如下:
01 view plaincopyprint?<?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03 android:layout_width="fill_parent"
04 android:layout_height="fill_parent"
05 android:orientation="vertical" >
06 <TextView
07 android:id="@+id/student"
08 android:layout_width="fill_parent"
09 android:layout_height="wrap_content"
10 android:text="@string/hello" />
11 <TextView
12 android:id="@+id/classes"
13 android:layout_width="fill_parent"
14 android:layout_height="wrap_content"
15 />
16 </LinearLayout>
17 <?xml version="1.0" encoding="utf-8"?>
18 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
19 android:layout_width="fill_parent"
20 android:layout_height="fill_parent"
21 android:orientation="vertical" >
22 <TextView
23 android:id="@+id/student"
24 android:layout_width="fill_parent"
25 android:layout_height="wrap_content"
26 android:text="@string/hello" />
27 <TextView
28 android:id="@+id/classes"
29 android:layout_width="fill_parent"
30 android:layout_height="wrap_content"
31 />
32 </LinearLayout>
33
最后要在AndroidMainfest.xml中添加访问网络权限:
01 view plaincopyprint?<?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
03 package="com.tutor.jsondemo"
04 android:versionCode="1"
05 android:versionName="1.0" >
06 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
07 <application
08 android:icon="@drawable/ic_launcher"
09 android:label="@string/app_name" >
10 <activity
11 android:name=".JSONDemoActivity"
12 android:label="@string/app_name" >
13 <intent-filter>
14 <action android:name="android.intent.action.MAIN" />
15 <category android:name="android.intent.category.LAUNCHER" />
16 </intent-filter>
17 </activity>
18 </application>
19 </manifest>
20 <?xml version="1.0" encoding="utf-8"?>
21 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
22 package="com.tutor.jsondemo"
23 android:versionCode="1"
24 android:versionName="1.0" >
25 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
26 <application
27 android:icon="@drawable/ic_launcher"
28 android:label="@string/app_name" >
29 <activity
30 android:name=".JSONDemoActivity"
31 android:label="@string/app_name" >
32 <intent-filter>
33 <action android:name="android.intent.action.MAIN" />
34 <category android:name="android.intent.category.LAUNCHER" />
35 </intent-filter>
36 </activity>
37 </application>
38 </manifest>
39