gson的安装和使用

简介:

gson的安装和使用

1.安装

422101-20171023101115473-1604755712.png

422101-20171023101300223-705615290.png

422101-20171023101308738-1682695550.png

422101-20171023101312816-923820504.png

2.布局

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

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"
        />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </ScrollView>

</LinearLayout>

3.查看声明

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "demo.jq.com.networktest"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.google.code.gson:gson:2.8.2'
}

4.创建接收数据的类

package demo.jq.com.networktest;

import java.lang.reflect.Array;

/**
 * @author jim
 */

public class ApiData {
    String[] data =new String[5];
    private Integer code;
    private String message;

    public String[] getData() {
        return data;
    }

    public void setData(String[] data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


}

5.主体动作

package demo.jq.com.networktest;

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

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author jim
 */

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView responseText;
    private static final String TAG = "MainActivity";


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

        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    OkHttpClient client = new OkHttpClient();


                    // post请求
                    RequestBody requestBody = new FormBody.Builder()
                            .add("type","1")
                            .build();


                    Request request = new Request.Builder()
                            .url("http://devmg.yunlutong.com/api/test/testApi")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();


                    // 解析json数据
                    parseJSONWithGSON(responseData);


                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 解析json
     * @param jsonData
     */
    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        ApiData apiData = gson.fromJson(jsonData, ApiData.class);
        Log.d(TAG,"code is" + apiData.getCode());
        Log.d(TAG,"message is" + apiData.getMessage());

        // 遍历数据
        for(int i = 0; i < apiData.getData().length; i++){
            Log.d(TAG,"data "+i+" is " + apiData.getData()[i]);
        }
    }


    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });

    }
}

422101-20171023102012691-1580011398.png

422101-20171023102121988-219080258.png


本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/7714921.html,如需转载请自行联系原作者

相关文章
|
JSON fastjson Java
FastJson、JackJson 以及 Gson 的区别
FastJson、JackJson 以及 Gson 是 Java 生态圈中三种常用的 Json 解析器,它们均可将 Java 对象序列化为 Json 格式的字符串,也可将 Json 字符串反序列化为 Java 对象。下面我们讨论一下三者在序列化和反序列化操作中的一些区别。
854 0
|
22天前
|
JSON fastjson Java
Gson与FastJson详解
综上,Gson和FastJson都是用于Java对象和JSON数据互相转换的优秀库,选择哪个取决于性能、功能需求和个人偏好。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
26 2
|
6月前
|
JSON 数据格式
gson坑
gson坑
34 0
|
6月前
|
JSON Java API
Gson基本使用
Gson基本使用
65 0
|
11月前
|
JSON 安全 fastjson
gson与fastjson
gson与fastjson
95 0
|
12月前
|
JSON Java API
Gson-更新中
Gson-更新中
125 0
|
JSON fastjson Java
scala使用Gson和FastJson解析JSON
kafka传过来的数据好多都是JSON格式,需要对其解析,抽取出应用需要的数据。Gson和FastJson是两个不错的解析工具,以后可能经常会使用到,记录一下,防止以后遗忘。
822 0
|
JSON 数据格式
GSON - 基础篇
GSON - 基础篇
170 0
|
JSON 数据可视化 fastjson
Gson 简单使用姿势小结
关于 Json 序列化的框架可以说比较多了,比如 Spring 默认的 Jackson,国内互联网用的比较多的 FastJson,本文则主要介绍一下 Gson 的简单使用姿势,并不会涉及到不同的 json 框架的性能对比
183 0
Gson 简单使用姿势小结
|
JSON 前端开发 JavaScript
JSON解析教程(Gson、FastJson、Jackson)
JSON解析教程(Gson、FastJson、Jackson)
JSON解析教程(Gson、FastJson、Jackson)