大家好,今天给大家分享下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工具类,代码如下:
1 package com.tutor.jsondemo; 2 3 import java.io.IOException; 4 import java.io.InputStreamReader; 5 import java.io.UnsupportedEncodingException; 6 7 import org.apache.http.HttpEntity; 8 import org.apache.http.HttpResponse; 9 import org.apache.http.client.methods.HttpGet; 10 import org.apache.http.impl.client.DefaultHttpClient; 11 import org.apache.http.params.BasicHttpParams; 12 import org.apache.http.protocol.HTTP; 13 import org.json.JSONException; 14 import org.json.JSONObject; 15 import android.util.Log; 16 17 /** 18 * @author frankiewei. 19 * Json封装的工具类. 20 */ 21 public class JSONUtil { 22 23 private static final String TAG = "JSONUtil"; 24 25 /** 26 * 获取json内容 27 * @param url 28 * @return JSONArray 29 * @throws JSONException 30 * @throws ConnectionException 31 */ 32 public static JSONObject getJSON(String url) throws JSONException, Exception { 33 34 return new JSONObject(getRequest(url)); 35 } 36 37 /** 38 * 向api发送get请求,返回从后台取得的信息。 39 * 40 * @param url 41 * @return String 42 */ 43 protected static String getRequest(String url) throws Exception { 44 return getRequest(url, new DefaultHttpClient(new BasicHttpParams())); 45 } 46 47 /** 48 * 向api发送get请求,返回从后台取得的信息。 49 * 50 * @param url 51 * @param client 52 * @return String 53 */ 54 protected static String getRequest(String url, DefaultHttpClient client) throws Exception { 55 String result = null; 56 int statusCode = 0; 57 HttpGet getMethod = new HttpGet(url); 58 Log.d(TAG, "do the getRequest,url="+url+""); 59 try { 60 //getMethod.setHeader("User-Agent", USER_AGENT); 61 62 HttpResponse httpResponse = client.execute(getMethod); 63 //statusCode == 200 正常 64 statusCode = httpResponse.getStatusLine().getStatusCode(); 65 Log.d(TAG, "statuscode = "+statusCode); 66 //处理返回的httpResponse信息 67 result = retrieveInputStream(httpResponse.getEntity()); 68 } catch (Exception e) { 69 Log.e(TAG, e.getMessage()); 70 throw new Exception(e); 71 } finally { 72 getMethod.abort(); 73 } 74 return result; 75 } 76 77 /** 78 * 处理httpResponse信息,返回String 79 * 80 * @param httpEntity 81 * @return String 82 */ 83 protected static String retrieveInputStream(HttpEntity httpEntity) { 84 85 int length = (int) httpEntity.getContentLength(); 86 //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. 87 //length==-1,下面这句报错,println needs a message 88 if (length < 0) length = 10000; 89 StringBuffer stringBuffer = new StringBuffer(length); 90 try { 91 InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8); 92 char buffer[] = new char[length]; 93 int count; 94 while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) { 95 stringBuffer.append(buffer, 0, count); 96 } 97 } catch (UnsupportedEncodingException e) { 98 Log.e(TAG, e.getMessage()); 99 } catch (IllegalStateException e) { 100 Log.e(TAG, e.getMessage()); 101 } catch (IOException e) { 102 Log.e(TAG, e.getMessage()); 103 } 104 return stringBuffer.toString(); 105 } 106 }
编写主Activity代码JSONDemoActivity,代码如下:
1 package com.tutor.jsondemo; 2 3 import org.json.JSONArray; 4 import org.json.JSONException; 5 import org.json.JSONObject; 6 7 import android.app.Activity; 8 import android.os.Bundle; 9 import android.widget.TextView; 10 11 public class JSONDemoActivity extends Activity { 12 13 /** 14 * 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2 15 */ 16 private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp"; 17 18 private TextView mStudentTextView; 19 20 private TextView mClassTextView; 21 22 23 @Override 24 public void onCreate(Bundle savedInstanceState) { 25 super.onCreate(savedInstanceState); 26 setContentView(R.layout.main); 27 28 setupViews(); 29 } 30 31 /** 32 * 初始化 33 */ 34 private void setupViews(){ 35 mStudentTextView = (TextView)findViewById(R.id.student); 36 mClassTextView = (TextView)findViewById(R.id.classes); 37 38 try { 39 //获取后台返回的Json对象 40 JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL); 41 42 //获得学生数组 43 JSONArray mJsonArray = mJsonObject.getJSONArray("students"); 44 //获取第一个学生 45 JSONObject firstStudent = mJsonArray.getJSONObject(0); 46 //获取班级 47 String classes = mJsonObject.getString("class"); 48 49 50 51 String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生." 52 + "第一个学生姓名: " + firstStudent.getString("name") 53 + " 年龄: " + firstStudent.getInt("age"); 54 55 mStudentTextView.setText(studentInfo); 56 57 mClassTextView.setText("班级: " + classes); 58 } catch (JSONException e) { 59 e.printStackTrace(); 60 } catch (Exception e) { 61 e.printStackTrace(); 62 } 63 } 64 65 66 }
这里用到的布局文件main.xml代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 7 <TextView 8 android:id="@+id/student" 9 android:layout_width="fill_parent" 10 android:layout_height="wrap_content" 11 android:text="@string/hello" /> 12 13 <TextView 14 android:id="@+id/classes" 15 android:layout_width="fill_parent" 16 android:layout_height="wrap_content" 17 /> 18 19 </LinearLayout>
最后要在AndroidMainfest.xml中添加访问网络权限:
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.tutor.jsondemo" 4 android:versionCode="1" 5 android:versionName="1.0" > 6 7 8 <uses-permission android:name="android.permission.INTERNET"></uses-permission> 9 <application 10 android:icon="@drawable/ic_launcher" 11 android:label="@string/app_name" > 12 <activity 13 android:name=".JSONDemoActivity" 14 android:label="@string/app_name" > 15 <intent-filter> 16 <action android:name="android.intent.action.MAIN" /> 17 18 <category android:name="android.intent.category.LAUNCHER" /> 19 </intent-filter> 20 </activity> 21 </application> 22 23 </manifest>
运行工程,效果如下:


浙公网安备 33010602011771号