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

摘要:
大家好,今天给大家分享下Android解析Json的例子,我这里自己安装了Tomcat,让自己电脑充当下服务器,最重要的是,返回结果自己可以随便修改。首先看下Json的定义,以及它和XML的比较: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首页界面,

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

我们在Tomcat安装目录下webapps\ROOT下找到index.jsp,然后新建一个index2.jsp,用记事本或者什么的,编辑内容如下:

{students:[{name:'魏祝林',age:25},{name:'阿魏',age:26}],class:'三年二班'}

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

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

新建一个Android工程JsonDemo.

工程目录如下:

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

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

packagecom.tutor.jsondemo;

importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.UnsupportedEncodingException;

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

/*** @authorfrankiewei.
 * Json封装的工具类.
 */
public classJSONUtil {
    
    private static final String TAG = "JSONUtil";
    
    /*** 获取json内容
     * @paramurl
     * @returnJSONArray
     * @throwsJSONException 
     * @throwsConnectionException 
     */
    public static JSONObject getJSON(String url) throwsJSONException, Exception {
        
        return newJSONObject(getRequest(url));
    }
    
    /*** 向api发送get请求,返回从后台取得的信息。
     * 
     * @paramurl
     * @returnString
     */
    protected static String getRequest(String url) throwsException {
        return getRequest(url, new DefaultHttpClient(newBasicHttpParams()));
    }
    
    /*** 向api发送get请求,返回从后台取得的信息。
     * 
     * @paramurl
     * @paramclient
     * @returnString
     */
    protected static String getRequest(String url, DefaultHttpClient client) throwsException {
        String result = null;
        int statusCode = 0;
        HttpGet getMethod = newHttpGet(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 newException(e);
        } finally{
            getMethod.abort();
        }
        returnresult;
    }
    
    /*** 处理httpResponse信息,返回String
     * 
     * @paramhttpEntity
     * @returnString
     */
    protected staticString 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 = newStringBuffer(length);
        try{
            InputStreamReader inputStreamReader = newInputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
            char buffer[] = new char[length];
            intcount;
            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());
        }
        returnstringBuffer.toString();
    }
}

编写主Activity代码JSONDemoActivity,代码如下:

packagecom.tutor.jsondemo;

importorg.json.JSONArray;
importorg.json.JSONException;
importorg.json.JSONObject;

importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.widget.TextView;

public class JSONDemoActivity extendsActivity {
    
    /*** 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2
     */
    private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp";
    
    privateTextView mStudentTextView;
    
    privateTextView mClassTextView;
    
    
    @Override
    public voidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        setupViews();
    }
    
    /*** 初始化
     */
    private voidsetupViews(){
        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代码如下:

<?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中添加访问网络权限:

<?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>

运行工程,效果如下:

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

转:http://blog.csdn.net/android_tutor/article/details/7466620

免责声明:文章转载自《Android 解析后台返回为Json数据的简单例子》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇【转载】C# MVC 实现登录的5种方式Nginx虚拟主机配置教程下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C#System.Text.RegularExpressions.Regex使用(二)

string x = "\\";Regex r1 = new Regex("^\\\\$");Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1Regex r2 = new Regex(@"^\\$");Console.WriteLine("r2 match count:" + r...

在内网服务器中获得真正的客户端ip的方法

如下代码: /**//// <summary>    /// RealIP 的摘要说明:    /// 获得用户的真实ip,由于squidserver的原因直接取到的ip是内网ip    /// </summary>    abstract public class RealIP    {        const string H...

windows下安装配置phpjavabridge,PHP调用自己的JAVA文件

方法一:(推荐方法 ) 使用php/java桥 JavaBridge.jar  转自:http://zhengdl126.iteye.com/blog/418574http://sourceforge.net/projects/php-java-bridge http://mirror.optus.net/sourceforge/p/ph/php-java...

使用事务和SqlBulkCopy批量插入数据

SqlBulkCopy是.NET Framework 2.0新增的类,位于命名空间System.Data.SqlClient下,主要提供把其他数据源的数据有效批量的加载到SQL Server表中的功能。类似与 Microsoft SQL Server 包中名为 bcp 的命令行应用程序。但是使用 SqlBulkCopy 类可以编写托管代码解决方案,性能上优...

Go 每日一库之 flag

缘起 我一直在想,有什么方式可以让人比较轻易地保持每日学习,持续输出的状态。写博客是一种方式,但不是每天都有想写的,值得写的东西。有时候一个技术比较复杂,写博客的时候经常会写着写着发现自己的理解有偏差,或者细节还没有完全掌握,要去查资料,了解了之后又继续写,如此反复。这样会导致一篇博客的耗时过长。 我在每天浏览思否、掘金和Github的过程中,发现一些比较...

Java中的ASCII、Unicode和UTF-8字符编码集

原文:@http://kxjhlele.iteye.com/blog/333211 首先讲一下几种字符的编码方式: 1. ASCII码 我们知道,在计算机内部,所有的信息最终都表示为一个二进制的字符串。每一个二进制位(bit)有0和1两种状态,因此八个二进制位就可以组合出256种状态,这被称为一个字节(byte)。也就是说,一个字节一共可以用来表示2...