安卓基础学习 Day18 |JSON解析库-Gson和FastJson

写在前面的话

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

一、概述

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

相较来说(在数据量不多的情况下),推荐使用Gson,因为功能较全面,使用也简单。

二、Gson-测试

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:id="@+id/tv_title1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="转换前的数据:"
        android:visibility="invisible"
        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:id="@+id/tv_title2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="转换后的数据:"
        android:visibility="invisible"
        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;
    private TextView tvTitle1,tvTitle2;

    @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);
        tvTitle1 = findViewById(R.id.tv_title1);
        tvTitle2 = findViewById(R.id.tv_title2);
        //监听
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
    }

    @Override
    //点击事件
    public void onClick(View v) {
        //标题显示为可见
        tvTitle1.setVisibility(View.VISIBLE);
        tvTitle2.setVisibility(View.VISIBLE);
        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时的显示顺序问题

三、FastJson-测试

1、Day19内容。
2、新知识。

FastJson:是一个Java语言编写的高性能功能完善的JSON库,是阿里巴巴的开源JSON解析库。除开Java与JSON 间的转换,最大的特点便是快。

(一)准备

1 导入库
在这里插入图片描述
2 布局略(类似Gson测试部分)

3 JAVA类略(同上理由)

(二)具体实现

MainActivity.java

package com.example.testfastjson;

import androidx.appcompat.app.AppCompatActivity;

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

import com.alibaba.fastjson.JSON;/

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;
    private TextView tvTitle1,tvTitle2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        initView();
        //初始化监听
        initListener();
    }

    private void initView() {
        //获取控件
        ///按钮部分
        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);
        ///标题部分
        tvTitle1 = findViewById(R.id.tv_title1);
        tvTitle2 = findViewById(R.id.tv_title2);
    }
    private void initListener() {
        //监听
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
    }

    @Override
    //点击事件
    public void onClick(View v) {
        //标题显示为可见
        tvTitle1.setVisibility(View.VISIBLE);
        tvTitle2.setVisibility(View.VISIBLE);

        switch (v.getId()){
            case R.id.btn_one:
                jsonToJavaByFastJson();
                break;
            case R.id.btn_two:
                jsonToJavaListByFastJson();
                break;
            case R.id.btn_three:
                javaToJsonByFastJson();
                break;
            case R.id.btn_four:
                javaListToJsonByFastJson();
                break;
        }
    }

    /**将JAVA对象的集合List转换为JSON字符串[]
     *JSON.toJSONString
     */
    private void javaListToJsonByFastJson() {
        List<TestJava> javaDatas = new ArrayList<>();
        TestJava testJava = new TestJava("FastJson2-1",1,"Test2-1");
        TestJava testJava1 = new TestJava("FastJson2-2",2,"Test2-2");
        javaDatas.add(testJava);
        javaDatas.add(testJava1);

        String jsonDatas = JSON.toJSONString(javaDatas);

        tv1.setText(javaDatas.toString());
        tv2.setText(jsonDatas);
    }
    /**将JAVA对象转换为JSON格式的字符串{}
     *JSON.toJSONString
     */
    private void javaToJsonByFastJson() {
        TestJava javaData = new TestJava("FastJson2",1,"Test2");
        String jsonData = JSON.toJSONString(javaData);
        tv1.setText(javaData.toString());
        tv2.setText(jsonData);
    }

    /**反序列
     * 将JSON字符串[]转换为JAVA对象的集合List
     * JSON.parseArray
     */
    private void jsonToJavaListByFastJson() {
        String jsonDatas = "[\n" +
                "{ \"name\":\"FastJson1-1\" , \"age\":\"1\", \"breed\":\"Test1-1\" },\n" +
                "\n" +
                "{ \"name\":\"FastJson1-2\" , \"age\":\"2\" , \"breed\":\"Test1-2\"},\n" +
                "\n" +
                "{ \"name\":\"FastJson1-3\" , \"age\":\"3\" , \"breed\":\"Test1-3\"}\n" +
                "]";
        List<TestJava> testJavaList = JSON.parseArray(jsonDatas, TestJava.class);
        tv1.setText(jsonDatas);
        tv2.setText(testJavaList.toString());
    }
    /**将JSON格式的字符串{}转换为JAVA对象
     *JSON.parseObject
     */
    private void jsonToJavaByFastJson() {
        String jsonData = "{\n" +
                "\"name\":\"FastJson1\",\n" +
                "\"age\":\"0\",\n" +
                "\"breed\":\"Test1\"\n" +
                "}\n";

        TestJava testJava = JSON.parseObject(jsonData, TestJava.class);//解析json数据

        tv1.setText(jsonData);
        tv2.setText(testJava.toString());
    }
}

(三)效果展示

运行结果如下。

(四)补充

Java基础学习总结——Java对象的序列化和反序列化

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值