androidAsyncTask及Gson的结合使用

android异步任务及Gson的结合使用

这段时间看见大部分程序猿们对于解析Json数据,都是喜欢使用Gson,所以我也试着学习了一下(原来我都是用JsonObiect来解析的,代码挺繁琐的)。

AndroidStudio的童鞋们,直接添加依赖Gson就可以直接使用了,方便快捷(具体的添加方法,百度,google一大把)。

下面是我的一段Json数据:String Json = "{"status":0,"responseParameters":{"companyid":"65","companyname":"朋金汽车服务有限公司"},"comment":"查询成功!"}"

首先:我们先来解析这个Json 数据,写一个bean文件

public class DriverAdd {
    private int status;
    private responseParameters responseParameters;
    private String comment;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public DriverAdd.responseParameters getResponseParameters() {
        return responseParameters;
    }

    public void setResponseParameters(DriverAdd.responseParameters responseParameters) {
        this.responseParameters = responseParameters;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public static class responseParameters {
        private String companyid;
        private String companyname;

        public String getCompanyid() {
            return companyid;
        }

        public void setCompanyid(String companyid) {
            this.companyid = companyid;
        }

        public String getCompanyname() {
            return companyname;
        }

        public void setCompanyname(String companyname) {
            this.companyname = companyname;
        }
    }
}
好了,有了bean,我们就可以进行下一步了。

然后:AsyncTask用法呢,就不多说了,网上一搜一大把,直接上代码

/**
     * android Gson 解析json
     */
    public class AsyncTaskGson extends AsyncTask<String, String, String> {
        private Context mContext;

        AsyncTaskGson(Context context) {
            this.mContext = context;
        }

        @Override
        protected String doInBackground(String... strings) {
            String mJson = "{\"status\":3,\"responseParameters\":{\"companyid\":\"65\",\"companyname\":\"临沂市朋金汽车服务有限公司\"},\"comment\":null}";
            try {
                //这个地方呢,就是模拟一个耗时操作,比如网络回去json啊,或者其他的什么数据传输,获取网络图片什么啊...
            } catch (JSONException e) {
                e.printStackTrace();
            }
            
            return mJson;
        }

        @Override
        protected void onPostExecute(String s) {
//            super.onPostExecute(s);
            Gson gson = new Gson();
			//这里为什么这么写呢,是因为有时候网络获取的json有的字段是“”,或者null,造成程序报错,这样就不会了,
			//自己也可以将上面的json字符串改成一个null试试,这里就不再演示了。
            Gson g = new GsonBuilder().serializeNulls().create(); 
            String json = s;
            //new 一个Product对象
            DriverAdd product = new DriverAdd();
            //将一个json字符串转换为java对象
            product = g.fromJson(json, DriverAdd.class); // DriverAdd 就是你的bean文件

            mIp_status.setText(product.getStatus() + "");
            mIp_comId.setText(product.getResponseParameters().getCompanyid());
            mIp_comName.setText(product.getResponseParameters().getCompanyname());
            mIp_Comment.setText(product.getComment());
            Toast.makeText(Test_Gson_AsyncTask.this, "执行完毕", Toast.LENGTH_SHORT).show();
        }
    }
到这里呢,就ok了,然后再在你的onCreate方法里面声明一下控件和启动这个异步任务:

 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_gson_asynctask);

        mIp_status = (TextView) findViewById(R.id.input_status);
        mIp_comId = (TextView) findViewById(R.id.input_comId);
        mIp_comName = (TextView) findViewById(R.id.input_comName);
        mIp_Comment = (TextView) findViewById(R.id.input_comment);

        if (IsNetwork.isNetwork(Test_Gson_AsyncTask.this)) {
            AsyncTaskGson taskGson = new AsyncTaskGson(Test_Gson_AsyncTask.this);
            taskGson.execute();
        } else {
            Toast.makeText(Test_Gson_AsyncTask.this, "你的网络不给力啊!", Toast.LENGTH_SHORT).show();
        }
    }

到这里呢,就基本玩完成了,但是千万别忘了manifest中添加网络权限 !

下面是layout布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@color/colorAccent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="TITTLE"
            android:textSize="18dp"
            android:textStyle="bold"/>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Status:"
            android:textStyle="bold"/>

        <TextView
            android:id="@+id/input_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="CompanyId:"
            android:textStyle="bold"/>

        <TextView
            android:id="@+id/input_comId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="CompanyName:"
            android:textStyle="bold"/>

        <TextView
            android:id="@+id/input_comName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Comment:"
            android:textStyle="bold"/>

        <TextView
            android:id="@+id/input_comment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>
</LinearLayout>


这样就ok了!!!



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值