Android 解析后台返回为Json数据的简单例子!!!

大家好,今天给大家分享下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:'三年二班'}
{students:[{name:'魏祝林',age:25},{name:'阿魏',age:26}],class:'三年二班'}

然后我们在浏览器里输入:http://localhost:8080/index2.jsp返回的结果如下(这就模拟出后台返回的数据了):

新建一个Android工程JsonDemo.

工程目录如下:


这里我封装了一个JSONUtil工具类,代码如下:


  1. package com.tutor.jsondemo;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.UnsupportedEncodingException;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import org.apache.http.params.BasicHttpParams;
  10. import org.apache.http.protocol.HTTP;
  11. import org.json.JSONException;
  12. import org.json.JSONObject;
  13. import android.util.Log;
  14. /**
  15. * @author frankiewei.
  16. * Json封装的工具类.
  17. */
  18. public class JSONUtil {
  19. private static final String TAG = "JSONUtil";
  20. /**
  21. * 获取json内容
  22. * @param url
  23. * @return JSONArray
  24. * @throws JSONException
  25. * @throws ConnectionException
  26. */
  27. public static JSONObject getJSON(String url) throws JSONException, Exception {
  28. return new JSONObject(getRequest(url));
  29. }
  30. /**
  31. * 向api发送get请求,返回从后台取得的信息。
  32. *
  33. * @param url
  34. * @return String
  35. */
  36. protected static String getRequest(String url) throws Exception {
  37. return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
  38. }
  39. /**
  40. * 向api发送get请求,返回从后台取得的信息。
  41. *
  42. * @param url
  43. * @param client
  44. * @return String
  45. */
  46. protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
  47. String result = null;
  48. int statusCode = 0;
  49. HttpGet getMethod = new HttpGet(url);
  50. Log.d(TAG, "do the getRequest,url="+url+"");
  51. try {
  52. //getMethod.setHeader("User-Agent", USER_AGENT);
  53. HttpResponse httpResponse = client.execute(getMethod);
  54. //statusCode == 200 正常
  55. statusCode = httpResponse.getStatusLine().getStatusCode();
  56. Log.d(TAG, "statuscode = "+statusCode);
  57. //处理返回的httpResponse信息
  58. result = retrieveInputStream(httpResponse.getEntity());
  59. } catch (Exception e) {
  60. Log.e(TAG, e.getMessage());
  61. throw new Exception(e);
  62. } finally {
  63. getMethod.abort();
  64. }
  65. return result;
  66. }
  67. /**
  68. * 处理httpResponse信息,返回String
  69. *
  70. * @param httpEntity
  71. * @return String
  72. */
  73. protected static String retrieveInputStream(HttpEntity httpEntity) {
  74. int length = (int) httpEntity.getContentLength();
  75. //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.
  76. //length==-1,下面这句报错,println needs a message
  77. if (length < 0) length = 10000;
  78. StringBuffer stringBuffer = new StringBuffer(length);
  79. try {
  80. InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
  81. char buffer[] = new char[length];
  82. int count;
  83. while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
  84. stringBuffer.append(buffer, 0, count);
  85. }
  86. } catch (UnsupportedEncodingException e) {
  87. Log.e(TAG, e.getMessage());
  88. } catch (IllegalStateException e) {
  89. Log.e(TAG, e.getMessage());
  90. } catch (IOException e) {
  91. Log.e(TAG, e.getMessage());
  92. }
  93. return stringBuffer.toString();
  94. }
  95. }
package com.tutor.jsondemo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

/**
 * @author frankiewei.
 * Json封装的工具类.
 */
public class JSONUtil {
	
	private static final String TAG = "JSONUtil";
	
	/**
	 * 获取json内容
	 * @param  url
	 * @return JSONArray
	 * @throws JSONException 
	 * @throws ConnectionException 
	 */
	public static JSONObject getJSON(String url) throws JSONException, Exception {
		
		return new JSONObject(getRequest(url));
	}
	
	/**
	 * 向api发送get请求,返回从后台取得的信息。
	 * 
	 * @param url
	 * @return String
	 */
	protected static String getRequest(String url) throws Exception {
		return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
	}
	
	/**
	 * 向api发送get请求,返回从后台取得的信息。
	 * 
	 * @param url
	 * @param client
	 * @return String
	 */
	protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
		String result = null;
		int statusCode = 0;
		HttpGet getMethod = new HttpGet(url);
		Log.d(TAG, "do the getRequest,url="+url+"");
		try {
			//getMethod.setHeader("User-Agent", USER_AGENT);

			HttpResponse httpResponse = client.execute(getMethod);
			//statusCode == 200 正常
			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "statuscode = "+statusCode);
			//处理返回的httpResponse信息
			result = retrieveInputStream(httpResponse.getEntity());
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new Exception(e);
		} finally {
			getMethod.abort();
		}
		return result;
	}
	
	/**
	 * 处理httpResponse信息,返回String
	 * 
	 * @param httpEntity
	 * @return String
	 */
	protected static String retrieveInputStream(HttpEntity httpEntity) {
				
		int length = (int) httpEntity.getContentLength();		
		//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.
		//length==-1,下面这句报错,println needs a message
		if (length < 0) length = 10000;
		StringBuffer stringBuffer = new StringBuffer(length);
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
			char buffer[] = new char[length];
			int count;
			while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
				stringBuffer.append(buffer, 0, count);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.getMessage());
		} catch (IllegalStateException e) {
			Log.e(TAG, e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		}
		return stringBuffer.toString();
	}
}
编写主Activity代码JSONDemoActivity,代码如下:

  1. package com.tutor.jsondemo;
  2. import org.json.JSONArray;
  3. import org.json.JSONException;
  4. import org.json.JSONObject;
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.widget.TextView;
  8. public class JSONDemoActivity extends Activity {
  9. /**
  10. * 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2
  11. */
  12. private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp";
  13. private TextView mStudentTextView;
  14. private TextView mClassTextView;
  15. @Override
  16. public void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. setupViews();
  20. }
  21. /**
  22. * 初始化
  23. */
  24. private void setupViews(){
  25. mStudentTextView = (TextView)findViewById(R.id.student);
  26. mClassTextView = (TextView)findViewById(R.id.classes);
  27. try {
  28. //获取后台返回的Json对象
  29. JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL);
  30. //获得学生数组
  31. JSONArray mJsonArray = mJsonObject.getJSONArray("students");
  32. //获取第一个学生
  33. JSONObject firstStudent = mJsonArray.getJSONObject(0);
  34. //获取班级
  35. String classes = mJsonObject.getString("class");
  36. String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生."
  37. + "第一个学生姓名: " + firstStudent.getString("name")
  38. + " 年龄: " + firstStudent.getInt("age");
  39. mStudentTextView.setText(studentInfo);
  40. mClassTextView.setText("班级: " + classes);
  41. } catch (JSONException e) {
  42. e.printStackTrace();
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }
package com.tutor.jsondemo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class JSONDemoActivity extends Activity {
    
	/**
	 * 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2
	 */
	private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp";
	
	private TextView mStudentTextView;
	
	private TextView mClassTextView;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        setupViews();
    }
    
    /**
     * 初始化
     */
    private void setupViews(){
    	mStudentTextView = (TextView)findViewById(R.id.student);
    	mClassTextView = (TextView)findViewById(R.id.classes);
    	
    	try {
    		//获取后台返回的Json对象
			JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL);
			
			//获得学生数组
			JSONArray mJsonArray = mJsonObject.getJSONArray("students");
			//获取第一个学生
			JSONObject firstStudent = mJsonArray.getJSONObject(0);
			//获取班级
			String classes = mJsonObject.getString("class");
			
			
			
			String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生."
					             + "第一个学生姓名: " + firstStudent.getString("name")
					             + " 年龄: " + firstStudent.getInt("age");
			
			mStudentTextView.setText(studentInfo);
			
			mClassTextView.setText("班级: " + classes);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    
}

这里用到的布局文件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. <TextView
  7. android:id="@+id/student"
  8. android:layout_width="fill_parent"
  9. 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>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/student"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    
    <TextView 
        android:id="@+id/classes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</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. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  7. <application
  8. android:icon="@drawable/ic_launcher"
  9. 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>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutor.jsondemo"
    android:versionCode="1"
    android:versionName="1.0" >

    
	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".JSONDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

运行工程,效果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值