当前位置:首页 » 《资源分享》 » 正文

使用GSON解析_indeedes的博客

19 人参与  2021年10月26日 15:43  分类 : 《资源分享》  评论

点击全文阅读


一、简介

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;
                }
            }
        }
    }
}

注意: 手动生成!!!


点击全文阅读


本文链接:http://zhangshiyu.com/post/30153.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1