前言

简单记录一下Gson的使用。Gson是Google提供的一个Java库,用于将Java对象转换为JSON格式数据或将JSON格式数据转换为Java对象。

开源的库

https://github.com/google/gson

正文

build.gradle中

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

下面简单记录一下相关方法的使用。

//初始化Gson
Gson mGson = new GsonBuilder().setPrettyPrinting().create();

定义一个Student类

public class Student {
    private final int age;
    private final String name;
    private final float score;

    public Student(int age, String name, float score) {
        this.age = age;
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public float getScore() {
        return score;
    }

    @NonNull
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}

toJson()和fromJson()都有重写,看具体传入的值,这里不深究。

toJson()

转换为Json数据。

示例1
Student student0 = new Student(18, "王麻", 699);
String studentString = mGson.toJson(student0);
Log.d(TAG, "studentString : "+ studentString);

输出结果

studentString : {
  "age": 18,
  "name": "王麻",
  "score": 699.0
}
示例2
ArrayList<Student> mList = new ArrayList<>();
//添加数据
mList.add(new Student(16, "张三", 500));
mList.add(new Student(17, "李四", 490));
mList.add(new Student(15, "王五", 580));

//转换为Gson
String listString  =  mGson.toJson(mList);
Log.d(TAG, "listString : "+ listString);

输出结果

listString : [
  {
    "age": 16,
    "name": "张三",
    "score": 500.0
  },
  {
    "age": 17,
    "name": "李四",
    "score": 490.0
  },
  {
    "age": 15,
    "name": "王五",
    "score": 580.0
  }
]

fromJson()

解析Json数据。这里对应上面toJson()

示例1
Student student = mGson.fromJson(studentString, Student.class);
Log.d(TAG, "student : "+ student);

输出结果

student : Student{age=18, name='王麻', score=699.0}
示例2
ArrayList<Student> studentList = mGson.fromJson(listString, new TypeToken<ArrayList<Student>>(){}.getType());
Log.d(TAG, "studentList : "+ studentList);

输出结果

studentList : [Student{age=16, name='张三', score=500.0}, Student{age=17, name='李四', score=490.0}, Student{age=15, name='王五', score=580.0}]

toJsonTree()

Student student = new Student(18, "王麻", 699);
JsonElement studentJsonElement = mGson.toJsonTree(student);
Log.d(TAG, "studentJsonElement : "+ studentJsonElement);

输出结果

studentJsonElement : {"age":18,"name":"王麻","score":699.0}

参考文章

  1. 使用Gson解析Json数据

相关文章

暂无评论

none
暂无评论...