Android筆記 (3): GsonFormat、FastJson

上一篇中,已經(jīng)能夠正確拿出api返回結(jié)果:

{"code":0,"data":{"country":"\u7f8e\u56fd","country_id":"US","area":"","area_id":"","region":"","region_id":"","city":"","city_id":"","county":"","county_id":"","isp":"","isp_id":"","ip":"21.22.11.33"}}

本節(jié)將講述快速將該結(jié)果轉(zhuǎn)換為實(shí)體。其中,用到Android Studio的一個(gè)插件GsonFormat,該插件可以將json生成對(duì)應(yīng)的java類,而FastJson相信大家都很熟悉了。
GsonFormat安裝方法參照該文:
插件GsonFormat快速實(shí)現(xiàn)JavaBean

1.Android studio File->Settings..->Plugins–>Browse repositores..搜索GsonFormat

安裝GsonFormat插件

2.安裝插件,重啟android studio

為了從結(jié)構(gòu)上更容易理解,現(xiàn)將MainActivity移至com.joyin.volleydemo.activity包中(記得修改AndroidManifest.xml),然后新建實(shí)體類com.joyin.volleydemo.data.api.IpInfo

新建實(shí)體類

在IpInfo類中,點(diǎn)擊Code->Generate或者右鍵選Generate都可以使用GsonFormat(快捷鍵alt+insert)。


使用GsonFormat
輸入剛才得到的返回值
點(diǎn)擊Form效果更直觀
選擇需要映射的元素

這里全選即可生成代碼

GsonFormat生成的代碼

至此,實(shí)體類生成已經(jīng)完成,圖多,實(shí)際操作步驟實(shí)際很少,玩過GsonFormat后真心覺得方便。接下來講述如何使用fastjson。

FastJson的基本使用

首先,在build.gradle中加入:

compile 'com.alibaba:fastjson:1.2.5'

再次強(qiáng)調(diào),該文章目前只講述分散的知識(shí)技能點(diǎn),以最原始的方式實(shí)現(xiàn),并非最佳實(shí)踐方式,后續(xù)專題文章中再強(qiáng)調(diào)簡(jiǎn)約、高效、性能等因素。
接下來我們將返回的數(shù)據(jù)中country,country_id,ip三個(gè)字段的值顯示出來。首先修改布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.joyin.volleydemo.MainActivity">

    <TextView
        android:id="@+id/tv_country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_country_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_ip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java

package com.joyin.volleydemo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.joyin.volleydemo.R;
import com.joyin.volleydemo.data.api.IpInfo;

public class MainActivity extends AppCompatActivity {

    TextView mTvCountry, mTvCountryId, mTvIP;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initData();
    }

    private void initViews() {
        mTvCountry = (TextView) findViewById(R.id.tv_country);
        mTvCountryId = (TextView) findViewById(R.id.tv_country_id);
        mTvIP = (TextView) findViewById(R.id.tv_ip);
    }

    private void initData() {
        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=21.22.11.33";
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d("demo", "response = " + s);
                IpInfo ipInfo = JSONObject.parseObject(s, IpInfo.class);
                setIpInfoToView(ipInfo);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("demo", "onErrorResponse: " + volleyError.getMessage());
            }
        });

        Volley.newRequestQueue(this).add(request);
    }

    private void setIpInfoToView(IpInfo ipInfo) {
        mTvCountry.setText(ipInfo.getData().getCountry());
        mTvCountryId.setText(ipInfo.getData().getCountry_id());
        mTvIP.setText(ipInfo.getData().getIp());
    }
}

核心代碼很簡(jiǎn)單,沒有做空判斷等處理,F(xiàn)astJson將json轉(zhuǎn)對(duì)象更簡(jiǎn)單,比如我們的項(xiàng)目中的:

IpInfo ipInfo = JSONObject.parseObject(s, IpInfo.class);

最終運(yùn)行的效果圖:

效果圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容