使用GSON 解析数据

GOSON 是 java 类库,用户将java对象转换为JSON数据,也可以将一个JSON字符串转化为对应的java对象

implementation 'com.google.code.gson:gson:2.8.1'

GSON类库在解析json数据中更加方便,简答,它可以将一段JSON格式的字符串自动转换为一个对象, 

{
    "id":101,
    "name":"sunmer",
    "age":28,
    "height":1.75
}

解析单个对象首先需要创建一个Information类,在该类中ID,名字,年龄,身高,并且为这些属性设置get()方法,

package com.example.testapplication.entity;

public class Information {
    public int id;
    public String name;
    public int age;
    public float height;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public float getHeight() {
        return height;
    }
}

然后创建GSON 对象,通过fromJson() 方法进行JSON数据解析,最后通过Information类中getId()方法获取JSON s数据中ID

Gson gson = new Gson(); // 创建GSON 对象

Information info = new gson.fromJson(json数据,Information.class); // 解析JSON数据

info.getId(); // 获取JSON数据中id

通常情况下,JSON数据包含多个对象,如果解析一段JSON数组就需要使用TypeToken类来帮忙,将需要解析数据类型传入到fromJson() 方法中

 

package com.example.testapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.testapplication.entity.Information;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GsonActivity extends ApplicationActivity{
    private Handler handler; // 定义一个Android.os.Handle对象
    private String result = ""; // 定义一个代表显示内容的字符串
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        final TextView step = (TextView) findViewById(R.id.text1); // 显示单日步数
        final TextView time = (TextView) findViewById(R.id.text2);//获取TextView显示单日时间
        final TextView heat = (TextView) findViewById(R.id.text3);//获取TextView显示单日热量
        final TextView km = (TextView) findViewById(R.id.text4); //获取TextView显示单日公里数
        final TextView step1 = (TextView) findViewById(R.id.text5);//获取TextView显示周步数
        final TextView time1 = (TextView) findViewById(R.id.text6);//获取TextView显示周时间
        final TextView heat1 = (TextView) findViewById(R.id.text7);//获取TextView显示周热量
        final TextView km1 = (TextView) findViewById(R.id.text8); //获取TextView显示周公里数

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                // 创建TextView二维数组
                TextView[][] tv = {
   
   {step, time, heat, km}, {step1, time1, heat1, km1}};
                // 创建解析JSON的类型
                Type listType = new TypeToken<ArrayList<Information>>(){}.getType();
                // 创建解析JSON类型
                ArrayList<Information> foos = new Gson().fromJson(result,listType);
                for(int i = 0;i < foos.size();i++){
                    tv[i][0].setText(foos.get(i).getStep());     //获取JSON中的步数值
                    tv[i][1].setText(foos.get(i).getTime());     //获取JSON中的时间值
                    tv[i][2].setText(foos.get(i).getHeat());     //获取JSON中的热量值
                    tv[i][3].setText(foos.get(i).getKm());       //获取JSON中的公里数
                }
                super.handleMessage(msg);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                send();
                Message m = handler.obtainMessage();
                handler.sendMessage(m);
            }
        }).start();
    }

    public void send(){
        // 请求地址
        String target = "http://192.168.0.105:8080/example/index.json";
        // 创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        // 创建网络请求
        Request request = new Request.Builder().get().url(target).build();

        try {
            // 创建请求响应
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();// 获取json数据
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
扫描二维码关注公众号,回复: 13331925 查看本文章
<?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:background="@drawable/bgjson"
    android:orientation="vertical"
    >
    <!--显示单日步数-->
    <TextView
        android:id="@+id/text1"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="55dp" />
    <!--显示单日时间-->
    <TextView
        android:id="@+id/text2"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp" />
    <!--显示单日热量-->
    <TextView
        android:id="@+id/text3"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp" />
    <!--显示单日公里-->
    <TextView
        android:id="@+id/text4"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp" />
    <!--显示周步数-->
    <TextView
        android:id="@+id/text5"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="65dp" />
    <!--显示周时间-->
    <TextView
        android:id="@+id/text6"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp" />
    <!--显示周热量-->
    <TextView
        android:id="@+id/text7"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp" />
    <!--显示周公里-->
    <TextView
        android:id="@+id/text8"
        style="@style/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp" />
</LinearLayout>

猜你喜欢

转载自blog.csdn.net/weixin_38107457/article/details/121324201