ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

安卓基础学习 Day18 |Gson库

2021-01-30 18:02:12  阅读:208  来源: 互联网

标签:name ShopInfo 安卓 breed gson public Day18 Gson


目录

写在前面的话

1、主要参考自:
2、内容如果有不对的,希望可以指出或补充。
3、新知识。

一、概述

JSON的数据格式(键值对):是手机端(客户端)和服务器端进行数据交换的最通用的一种格式。Json 的解析和生成的方式很多,在 Android 平台上最常用的类库有 Gson 和 FastJson 两种。

Gson(又称Google Gson):是一个Java语言编写的用于处理JSON数据格式的开源应用程序编程接口项目。它将Java对象转换为JSON表示,还可以用于将JSON字符串转换为等效的Java对象。其实就是处理JSON格式数据的一个开源的Java类库

二、测试

(一)准备

1 依赖

应用对应的 build.gradle 文件
在这里插入图片描述
2 布局

activity_main.xml

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:background="@mipmap/bg"
    android:gravity="bottom">
    <!--展示部分-->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="转换前的数据:"
        android:textSize="15sp"
        android:textColor="@color/white"/>
    <TextView
        android:id="@+id/tv_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:textColor="#436EEE"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="转换后的数据:"
        android:textSize="15sp"
        android:textColor="@color/white"/>
    <TextView
        android:id="@+id/tv_two"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:textColor="#436EEE"/>
    <!--按钮部分-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:id="@+id/btn_one"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="将JSON对象转换为JAVA对象"
            android:textSize="15sp"/>
        <Button
            android:id="@+id/btn_two"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="将JSON数组转换为JAVA集合"
            android:textSize="15sp"/>
        <Button
            android:id="@+id/btn_three"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="将JAVA对象转换为JSON对象"
            android:textSize="15sp" />
        <Button
            android:id="@+id/btn_four"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="将JAVA集合转换为JSON数组"
            android:textSize="15sp"/>
    </LinearLayout>
</LinearLayout>

3 JAVA类

ShopInfo.java

package com.example.testgson;

public class ShopInfo {
    private String name;
    private int age;
    private String breed;

    public ShopInfo(String name, int age, String breed) {
        this.name = name;
        this.age = age;
        this.breed = breed;
    }

    public ShopInfo() { }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    @Override
    public String toString() {
        return "ShopInfo{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", breed='" + breed + '\'' +
                '}';
    }
}

(二)具体实现

方法其实都比较相似,可举一反三。

MainActivity.java

package com.example.testgson;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btn1,btn2,btn3,btn4;
    private TextView tv1,tv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取控件
        btn1 = findViewById(R.id.btn_one);
        btn2 = findViewById(R.id.btn_two);
        btn3 = findViewById(R.id.btn_three);
        btn4 = findViewById(R.id.btn_four);
        tv1 = findViewById(R.id.tv_one);
        tv2 = findViewById(R.id.tv_two);
        //监听
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
    }

    @Override
    //点击事件
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_one:
                jsonToJava();
                break;
            case R.id.btn_two:
                jsonToJavaList();
                break;
            case R.id.btn_three:
                javaToJson();
                break;
            case R.id.btn_four:
                javaListToJson();
                break;
        }
    }

    /**将JSON对象{}转换为JAVA对象
     *
     */
    private void jsonToJava() {
        //创建json数据
        String json = "{\n" +
                "\"name\":\"猫猫\",\n" +
                "\"age\":\"2\",\n" +
                "\"breed\":\"橘猫\"\n" +
                "}\n";
        //解析json数据
        Gson gson = new Gson();//Gson对象
        //Gson 也提供了 toJson() 和 fromJson() 两个方法用于转化 Model 与 Json
        // 前者实现了序列化,后者实现了反序列化
        ShopInfo shopInfo = gson.fromJson(json, ShopInfo.class);//参数1:需要解析的json数据,参数2:解析后生成的java类
        //展示数据
        tv1.setText(json);
        tv2.setText(shopInfo.toString());
    }

    //将JSON数组[]转换为JAVA集合List
    private void jsonToJavaList() {
        String json = "[\n" +
                "{ \"name\":\"大猫\" , \"age\":\"2\", \"breed\":\"橘猫\" },\n" +
                "\n" +
                "{ \"name\":\"帅猫\" , \"age\":\"1\" , \"breed\":\"缅因猫\"},\n" +
                "\n" +
                "{ \"name\":\"可爱猫\" , \"age\":\"2\" , \"breed\":\"布偶猫\"}\n" +
                "]";
        Gson gson = new Gson();//创建gson对象
        List<ShopInfo> shopInfoList = gson.fromJson(json, new TypeToken<List<ShopInfo>>(){
        }.getType());
        //展示数据
        tv1.setText(json);
        tv2.setText(shopInfoList.toString());
    }

    /**将JAVA对象转换为JSON对象{}
     *
     */
    private void javaToJson() {
        //创建java对象
        ShopInfo shopInfo = new ShopInfo("猫",2,"橘猫");
        //生成json对象
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(ShopInfo.class,new Show())
                .create();//通过 GsonBuilder 来获取,可以进行多项特殊配置
        String json = gson.toJson(shopInfo);
        //展示数据
        tv1.setText(shopInfo.toString());
        tv2.setText(json);
    }

    //将JAVA集合List转换为JSON数组[]
    private void javaListToJson() {
        //Java数据
        List<ShopInfo> shopInfos = new ArrayList<>();
        ShopInfo shopInfo = new ShopInfo("猫1",2,"橘猫");
        ShopInfo shopInfo2 = new ShopInfo("猫2",1,"挪威森林猫");
        shopInfos.add(shopInfo);
        shopInfos.add(shopInfo2);
        //
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(ShopInfo.class,new Show())
                .create();
        String json = gson.toJson(shopInfos);
        //
        tv1.setText(shopInfos.toString());
        tv2.setText(json);
    }

    //自定义显示顺序-解决显示顺序问题
    //参考自:https://blog.csdn.net/a254837127/article/details/103061930?utm_source=app&app_version=4.5.0
    public class Show extends TypeAdapter<ShopInfo> {
        @Override
        public void write(JsonWriter out, ShopInfo value) throws IOException {
            out.beginObject();
            //按自定义顺序输出字段信息
            out.name("name").value(value.getName());
            out.name("age").value(value.getAge());
            out.name("breed").value(value.getBreed());
            out.endObject();
        }
        @Override
        public ShopInfo read(JsonReader in) throws IOException {
            return null;
        }
    }
}

(三)效果

运行效果如下。

三、补充

1、Android Gson使用详解

2、Android Studio中如何导入Google Gson包

3、gson字段排序—解决JAVA→JSON时的显示顺序问题

标签:name,ShopInfo,安卓,breed,gson,public,Day18,Gson
来源: https://blog.csdn.net/luck_ch09/article/details/113427129

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有