一、簡介
GSON是Google提供的用來在Java物件和JSON資料之間進行映射的Java類別庫, 可以將一個Json字串轉換成一個Java物件,戒者將一個Java物件轉換成Json字串,
GSON最大的特點:(1)代碼量少、簡潔(2)資料傳遞和決議方便,
GSON的專案主頁地址是:https://github.com/google/gson
注意:添加GSON庫的依賴: implementation 'com.google.code.gson:gson:2.8.6'
1、GSON庫提供的方法
| 函式 | 函式 |
|---|---|
| toJson() | 將Java物件轉化為json字串 |
| fromJson() | 將json字串轉化為Java物件 |
? Serialization:序列化,Java物件轉化為Json字串,====》toJson()
? Deserialization:反序列化,Json字串轉化為Java物件, ====》fromJson()
2、JSON字串的決議
舉例:
假設從服務器上回傳的結果是一個JSON格式的字串,如下所示:
{“name”:”張三” ,”age”:20 }
【思路】定義Person類,并加入name和age這兩個欄位,然后呼叫GSON庫就可以很輕 松地實作將JSON字串自動決議成一個Person類的物件,
//Person類 public class Person { public String name; //姓名 public int age; //年齡 //構造方法 Person(String name,int age){ this.name = name ; this.age = age; } }

3、JSON陣列的決議
從介面回傳的資料格式中可以収現,學生陣列資訊存放在 “students”的區域內,而且資料格式是一個JSON陣列,
步驟1 ?定義一個ResponseClass類,用于將JSON字串轉化為JAVA物件
步驟2 ?定義一個Student類,用于獲取“students”區域內的學生資料
步驟3 ?使用GSON決議服務器回傳的JSON格式的資料
(1)步驟1:ResponseClass類的定義:
public class ResponseClass{
private String school;
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
注意 : 屬性的命名一定要和JSON 字串中的索引值一致
(2)步驟2: Student類 的定義:
public class Student{
private int id;
private String name;
private String sex;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
……..
}
注意 : 屬性的命名一定要和JSON 字串中的索引值一致
(3)步驟3:使用GSON開源庫迚行決議:

new TypeToken(){}.getType(); 為什么后面要跟上{}?
表示new的是一個匿名內部類的物件,該匿名類繼承自TypeToken,可以 在大括號里面像寫其他普通類代碼,但這里的{}里面什么都沒有寫,因為我們 只需要用到父類的一個public方法而已,
匿名內部類常用在監聽里面,例如給按鈕設定監聽事件:
button = findViewById(R.id.btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } } );setOnClickListener()方法接受的是一個OnClickListener型別的物件,而OnClickListener 是一個介面,不能直接采用new生成物件,需要自定義一個類實作OnClickListener介面, 然后再給他傳一個實作類的物件,但是那樣太麻煩,更多時候是直接在這里創建實作類, 卻沒有給他取名字,所以叫匿名,并同時在這里實作了抽象方法,
(4)補充

二、代碼講解
1、activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
2、MainActivity.java
package com.example.zsgson;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
//1.定義一個字串變數,用來存放HTTP請求的地址
public static final String address = "http://v.juhe.cn/weather/index?format=2&cityname=蘇州&key=ccfadb3491e63c1c3556f3ceb19e1237";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//2.呼叫工具類的sendOkHttpRequest()方法,獲取服務器回傳的天氣資訊
HttpUtil.sendOkHttpRequest(address,new okhttp3.Callback(){
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//定義一個字串變數responseData,存放服務器回傳的json資料
String responseData = response.body().string();
//創建GSON類的物件
Gson gson = new Gson();
//呼叫fromJson()方法將json字串轉換為Java物體類的物件
JsonToBean jsonToBean = gson.fromJson(responseData,new TypeToken<JsonToBean>(){}.getType());
//后面的操作就是Java類的操作了
JsonToBean.ResultBean resultBean = jsonToBean.getResult();
List<JsonToBean.ResultBean.FutureBean> futureBeanList = resultBean.getFuture();
for(int i=0 ;i<futureBeanList.size();i++){
JsonToBean.ResultBean.FutureBean futureBean = futureBeanList.get(i);
Log.d("MainActivity","temperature:"+futureBean.getTemperature()+" "+"weather:"+futureBean.getWeather()+" "+"wind:"+futureBean.getWind()+" "+"week:"+futureBean.getWeek()+"date:"+futureBean.getDate());
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
});
}
}
3、HttpUtil.java
package com.example.zsgson;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class HttpUtil {
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
//通過okHttp框架的異步請求方式來完成資料的抓取
//1.獲得OkHttpClient類的實體
OkHttpClient client = new OkHttpClient();
//2.創建Request物件,并通過屬性設定目標網路地址,請求方式等
Request request = new Request.Builder()
.url(address) //將第一個引數傳入url屬性
.build();
//3.通過OkHttpClient類的實體呼叫newCall()方法來創建call物件,并把異步請求的結果送入回呼介面
client.newCall(request).enqueue(callback);
}
}
4、JsonToBean.java
package com.example.zsgson;
import java.util.List;
public class JsonToBean {
/**
* resultcode : 200
* reason : 查詢成功
* result : {"sk":{"temp":"25","wind_direction":"東南風","wind_strength":"3級","humidity":"65%","time":"11:09"},"today":{"temperature":"17℃~26℃","weather":"小雨","weather_id":{"fa":"07","fb":"07"},"wind":"東南風3-5級","week":"星期五","city":"蘇州","date_y":"2020年05月29日","dressing_index":"舒適","dressing_advice":"建議著長袖T恤、襯衫加單褲等服裝,年老體弱者宜著針織長袖襯衫、馬甲和長褲,","uv_index":"最弱","comfort_index":"","wash_index":"不宜","travel_index":"較不宜","exercise_index":"較不宜","drying_index":""},"future":[{"temperature":"17℃~26℃","weather":"小雨","weather_id":{"fa":"07","fb":"07"},"wind":"東南風3-5級","week":"星期五","date":"20200529"},{"temperature":"17℃~22℃","weather":"小雨轉陰","weather_id":{"fa":"07","fb":"02"},"wind":"東風3-5級","week":"星期六","date":"20200530"},{"temperature":"21℃~28℃","weather":"陰","weather_id":{"fa":"02","fb":"02"},"wind":"東南風微風","week":"星期日","date":"20200531"},{"temperature":"21℃~29℃","weather":"小雨轉陰","weather_id":{"fa":"07","fb":"02"},"wind":"東南風3-5級","week":"星期一","date":"20200601"},{"temperature":"24℃~31℃","weather":"陰轉小雨","weather_id":{"fa":"02","fb":"07"},"wind":"南風微風","week":"星期二","date":"20200602"},{"temperature":"17℃~22℃","weather":"小雨轉陰","weather_id":{"fa":"07","fb":"02"},"wind":"東風3-5級","week":"星期三","date":"20200603"},{"temperature":"21℃~28℃","weather":"陰","weather_id":{"fa":"02","fb":"02"},"wind":"東南風微風","week":"星期四","date":"20200604"}]}
* error_code : 0
*/
private String resultcode;
private String reason;
private ResultBean result;
private int error_code;
public String getResultcode() {
return resultcode;
}
public void setResultcode(String resultcode) {
this.resultcode = resultcode;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public static class ResultBean {
/**
* sk : {"temp":"25","wind_direction":"東南風","wind_strength":"3級","humidity":"65%","time":"11:09"}
* today : {"temperature":"17℃~26℃","weather":"小雨","weather_id":{"fa":"07","fb":"07"},"wind":"東南風3-5級","week":"星期五","city":"蘇州","date_y":"2020年05月29日","dressing_index":"舒適","dressing_advice":"建議著長袖T恤、襯衫加單褲等服裝,年老體弱者宜著針織長袖襯衫、馬甲和長褲,","uv_index":"最弱","comfort_index":"","wash_index":"不宜","travel_index":"較不宜","exercise_index":"較不宜","drying_index":""}
* future : [{"temperature":"17℃~26℃","weather":"小雨","weather_id":{"fa":"07","fb":"07"},"wind":"東南風3-5級","week":"星期五","date":"20200529"},{"temperature":"17℃~22℃","weather":"小雨轉陰","weather_id":{"fa":"07","fb":"02"},"wind":"東風3-5級","week":"星期六","date":"20200530"},{"temperature":"21℃~28℃","weather":"陰","weather_id":{"fa":"02","fb":"02"},"wind":"東南風微風","week":"星期日","date":"20200531"},{"temperature":"21℃~29℃","weather":"小雨轉陰","weather_id":{"fa":"07","fb":"02"},"wind":"東南風3-5級","week":"星期一","date":"20200601"},{"temperature":"24℃~31℃","weather":"陰轉小雨","weather_id":{"fa":"02","fb":"07"},"wind":"南風微風","week":"星期二","date":"20200602"},{"temperature":"17℃~22℃","weather":"小雨轉陰","weather_id":{"fa":"07","fb":"02"},"wind":"東風3-5級","week":"星期三","date":"20200603"},{"temperature":"21℃~28℃","weather":"陰","weather_id":{"fa":"02","fb":"02"},"wind":"東南風微風","week":"星期四","date":"20200604"}]
*/
private SkBean sk;
private TodayBean today;
private List<FutureBean> future;
public SkBean getSk() {
return sk;
}
public void setSk(SkBean sk) {
this.sk = sk;
}
public TodayBean getToday() {
return today;
}
public void setToday(TodayBean today) {
this.today = today;
}
public List<FutureBean> getFuture() {
return future;
}
public void setFuture(List<FutureBean> future) {
this.future = future;
}
public static class SkBean {
/**
* temp : 25
* wind_direction : 東南風
* wind_strength : 3級
* humidity : 65%
* time : 11:09
*/
private String temp;
private String wind_direction;
private String wind_strength;
private String humidity;
private String time;
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getWind_direction() {
return wind_direction;
}
public void setWind_direction(String wind_direction) {
this.wind_direction = wind_direction;
}
public String getWind_strength() {
return wind_strength;
}
public void setWind_strength(String wind_strength) {
this.wind_strength = wind_strength;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public static class TodayBean {
/**
* temperature : 17℃~26℃
* weather : 小雨
* weather_id : {"fa":"07","fb":"07"}
* wind : 東南風3-5級
* week : 星期五
* city : 蘇州
* date_y : 2020年05月29日
* dressing_index : 舒適
* dressing_advice : 建議著長袖T恤、襯衫加單褲等服裝,年老體弱者宜著針織長袖襯衫、馬甲和長褲,
* uv_index : 最弱
* comfort_index :
* wash_index : 不宜
* travel_index : 較不宜
* exercise_index : 較不宜
* drying_index :
*/
private String temperature;
private String weather;
private WeatherIdBean weather_id;
private String wind;
private String week;
private String city;
private String date_y;
private String dressing_index;
private String dressing_advice;
private String uv_index;
private String comfort_index;
private String wash_index;
private String travel_index;
private String exercise_index;
private String drying_index;
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public WeatherIdBean getWeather_id() {
return weather_id;
}
public void setWeather_id(WeatherIdBean weather_id) {
this.weather_id = weather_id;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDate_y() {
return date_y;
}
public void setDate_y(String date_y) {
this.date_y = date_y;
}
public String getDressing_index() {
return dressing_index;
}
public void setDressing_index(String dressing_index) {
this.dressing_index = dressing_index;
}
public String getDressing_advice() {
return dressing_advice;
}
public void setDressing_advice(String dressing_advice) {
this.dressing_advice = dressing_advice;
}
public String getUv_index() {
return uv_index;
}
public void setUv_index(String uv_index) {
this.uv_index = uv_index;
}
public String getComfort_index() {
return comfort_index;
}
public void setComfort_index(String comfort_index) {
this.comfort_index = comfort_index;
}
public String getWash_index() {
return wash_index;
}
public void setWash_index(String wash_index) {
this.wash_index = wash_index;
}
public String getTravel_index() {
return travel_index;
}
public void setTravel_index(String travel_index) {
this.travel_index = travel_index;
}
public String getExercise_index() {
return exercise_index;
}
public void setExercise_index(String exercise_index) {
this.exercise_index = exercise_index;
}
public String getDrying_index() {
return drying_index;
}
public void setDrying_index(String drying_index) {
this.drying_index = drying_index;
}
public static class WeatherIdBean {
/**
* fa : 07
* fb : 07
*/
private String fa;
private String fb;
public String getFa() {
return fa;
}
public void setFa(String fa) {
this.fa = fa;
}
public String getFb() {
return fb;
}
public void setFb(String fb) {
this.fb = fb;
}
}
}
public static class FutureBean {
/**
* temperature : 17℃~26℃
* weather : 小雨
* weather_id : {"fa":"07","fb":"07"}
* wind : 東南風3-5級
* week : 星期五
* date : 20200529
*/
private String temperature;
private String weather;
private WeatherIdBeanX weather_id;
private String wind;
private String week;
private String date;
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public WeatherIdBeanX getWeather_id() {
return weather_id;
}
public void setWeather_id(WeatherIdBeanX weather_id) {
this.weather_id = weather_id;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public static class WeatherIdBeanX {
/**
* fa : 07
* fb : 07
*/
private String fa;
private String fb;
public String getFa() {
return fa;
}
public void setFa(String fa) {
this.fa = fa;
}
public String getFb() {
return fb;
}
public void setFb(String fb) {
this.fb = fb;
}
}
}
}
}
注意: 手動生成!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/300143.html
標籤:其他
上一篇:Android備忘錄專案總結

