Gson的一些笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lys1695227550/article/details/79605909
package entity; 
 

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Student {
    
    private String userName;
    private String sex;
    private int age;
    private List<String> book;
    private HashMap<String, String> map;

    public Student() {
    }
    public Student(String username) {
        this.userName=username;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    public List<String> getBook() {
        return book;
    }

    public void setBook(List<String> book) {
        this.book = book;
    }

    public String toString() {
        return "Student [userName=" + userName + ", sex=" + sex + ", age=" + age + ", book=" + book + ", map=" + map
                + "]";
    }

    public HashMap<String, String> getMap() {
        return map;
    }

    public void setMap(HashMap<String, String> map) {
        this.map = map;
    }

}


package entity;

import java.util.Arrays;

public class ClassRoom {
    private String roomName;
    private Student[] student;
    public String getRoomName() {
        return roomName;
    }
    public void setRoomName(String roomName) {
        this.roomName = roomName;
    }
    public Student[] getStudent() {
        return student;
    }
    public void setStudent(Student[] student) {
        this.student = student;
    }
    @Override
    public String toString() {
        return "ClassRoom [roomName=" + roomName + ", student=" + Arrays.toString(student) + "]";
    }
    
}

package json;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;

import org.apache.commons.collections.map.HashedMap;

import com.google.gson.Gson;

import entity.ClassRoom;
import entity.Student;

public class goson {
    public static void main(String[] args) {
//  function();
//    function2();
  function3();
//  function5();

    }

//    运行结果
/*    [Student [userName=name0, sex=null, age=0, book=null, map=null], Student [userName=name1, sex=null, age=0, book=null, map=null], Student [userName=name2, sex=null, age=0, book=null, map=null]]
            [{"userName":"name0","age":0},{"userName":"name1","age":0},{"userName":"name2","age":0}]
            Student [userName=name0, sex=null, age=0, book=null, map=null]
            Student [userName=name1, sex=null, age=0, book=null, map=null]
            Student [userName=name2, sex=null, age=0, book=null, map=null]*/

    private static void function3() {
        Gson gson = new Gson();
        Student student = null;
        ArrayList<Student> stuList = new ArrayList<Student>();
        for (int i = 0; i < 3; i++) {
            student = new Student("name" + i);
            stuList.add(student);
        }
        System.out.println(stuList);
        String jsonstr = gson.toJson(stuList);
        System.out.println(jsonstr);

        Student[] stus = gson.fromJson(jsonstr, Student[].class);
//        lambda表达式
        Stream<Student> stream = Stream.of(stus);
        stream.forEach(System.out::println);
    }
//运行结果
/*    {"roomName":"room1","student":[{"userName":"lailai","sex":"男","age":10,"book":["book1","book2","book3"],"map":{"k1":"kk","k2":"pp","k3":"oo"}},{"userName":"yang","age":30}]}
    ClassRoom [roomName=room1, student=[Student [userName=lailai, sex=男, age=10, book=[book1, book2, book3], map={k1=kk, k2=pp, k3=oo}], Student [userName=yang, sex=null, age=30, book=null, map=null]]]
*/
    private static void function2() {
        // TODO Auto-generated method stub
        Gson gson = new Gson();
        Student student = new Student();
        student.setUserName("lailai");
        List<String> bookList = Arrays.asList("book1", "book2", "book3");
        student.setBook(bookList);
        student.setAge(10);
        student.setSex("男");
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("k1", "kk");
        hashMap.put("k2", "pp");
        hashMap.put("k3", "oo");
        student.setMap(hashMap);
        Student student2 = new Student();
        student2.setUserName("yang");
        student2.setAge(30);
        Student[] ss = { student, student2 };
        ClassRoom classRoom = new ClassRoom();
        classRoom.setRoomName("room1");
        classRoom.setStudent(ss);
        String classRoomJson = gson.toJson(classRoom);
        System.out.println(classRoomJson);
        ClassRoom room = gson.fromJson(classRoomJson, ClassRoom.class);
        System.out.println(room);
    }
//运行结果
/*    Student [userName=lailai, sex=男, age=10, book=[book1, book2, book3], map={k1=kk, k2=pp, k3=oo}]
            {"userName":"lailai","sex":"男","age":10,"book":["book1","book2","book3"],"map":{"k1":"kk","k2":"pp","k3":"oo"}}
            Student [userName=lailai, sex=男, age=10, book=[book1, book2, book3], map={k1=kk, k2=pp, k3=oo}]
*/
    private static void function5() {
        Student student = new Student();
        student.setUserName("lailai");
        // ArrayList<String> bookList = new ArrayList<String>();
        List<String> bookList = Arrays.asList("book1", "book2", "book3");
        student.setBook(bookList);
        student.setAge(10);
        student.setSex("男");
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("k1", "kk");
        hashMap.put("k2", "pp");
        hashMap.put("k3", "oo");
        student.setMap(hashMap);
        System.out.println(student);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(student);
        System.out.println(jsonStr);

        Student stu = gson.fromJson(jsonStr, Student.class);
        System.out.println(stu);
    }
//运行结果
/*    1
    3.14
    "lailai"
    true
    1
    3.14
    false
    true
*/
    private static void function() {

        Gson gson = new Gson();
        // 基本数据类型解析
        String intJson = gson.toJson(1, int.class);
        String doubleJson = gson.toJson(3.14, double.class);
        String booleanJson = gson.toJson(true, boolean.class);
        // String是引用数据类型
        String stringJson = gson.toJson("lailai", String.class);
        System.out.println(intJson);
        System.out.println(doubleJson);
        System.out.println(stringJson);
        System.out.println(booleanJson);

        System.out.println(gson.fromJson(intJson, int.class));
        System.out.println(gson.fromJson(doubleJson, double.class));
        System.out.println(gson.fromJson(stringJson, boolean.class));
        System.out.println(gson.fromJson(booleanJson, String.class));

        // 泛型使用

    }
}


package entity;

import com.google.gson.annotations.Expose;

public class Person {
//    默认值都为 true,serialize序列化,deserialize反序列化
    @Expose(serialize=true,deserialize=false)
    private String userName;    
    @Expose(serialize=false,deserialize=false)
    private String sex;
//    不标记都可以@Expose()
    @Expose
    private int age;
    
//  使用了transient
    @Expose
    transient private boolean  test;
    
    
    

    public Person(String userName, String sex, int age, boolean test) {
        super();
        this.userName = userName;
        this.sex = sex;
        this.age = age;
        this.test = test;
    }

    public boolean isTest() {
        return test;
    }

    public void setTest(boolean test) {
        this.test = test;
    }

    public Person(String userName, String sex, int age) {
        super();
        this.userName = userName;
        this.sex = sex;
        this.age = age;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Person [userName=" + userName + ", sex=" + sex + ", age=" + age + ", test=" + test + "]";
    }



}


package entity;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Since;

public class people {
     @SerializedName("userNameeee")  
     @Since(1)
    private String userName;
     @SerializedName("sexxxx")
     @Since(2)
    private String sex;
    private int age;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "people [userName=" + userName + ", sex=" + sex + ", age=" + age + "]";
    }
    public people(String userName, String sex, int age) {
        super();
        this.userName = userName;
        this.sex = sex;
        this.age = age;
    }
    
}


package json;

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Since;

import entity.Person;
import entity.people;

//使用注解
/*Gson提供了GsonBuilder,我们可以用GsonBuilder来生成Gson对象,规定Gson的序列化或反序列化的格式。*/
//1.     使用注解自定义哪些字段需要序列化或反序列化,
//没有@Expose注解的不会被序列化,
//serialize为false代表不序列化,
//deserialize则代表反序列化:
public class gsonDemo {
    public static void main(String[] args) {
        Person person = new Person("lailai", "男", 13,true);
        Person person1 = new Person("yang", "女", 14,false);
        Person person2 = new Person("java", "男", 15,true);
    
        ArrayList<Person> personList = new ArrayList<Person>();
        
        personList.add(person);
        personList.add(person1);
        personList.add(person2);
        
        
        people people = new people("lailai", "男", 13);
        people people1 = new people("yang", "女", 14);
        people people2 = new people("java", "男", 15);
        
        ArrayList<people> perpleList = new ArrayList<people>();
        perpleList.add(people);
        perpleList.add(people1);
        perpleList.add(people2);
        
//        function(person, personList);
//        function2(people, perpleList);

        function3(people, perpleList);
    }

    
//    ,有些字段可能是后加的,设置版本,序列化时会区分
/*  @SerializedName("userNameeee")  
     @Since(1)
    private String userName;
     @SerializedName("sexxxx")
     @Since(2)
    private String sex;
    private int age;*/
//    版本设置2,运行结果,低于或者等于或者没有 @Since注解的都会序列化
//    {"userNameeee":"lailai","sexxxx":"男","age":13}
//    [{"userNameeee":"lailai","sexxxx":"男","age":13},{"userNameeee":"yang","sexxxx":"女","age":14},{"userNameeee":"java","sexxxx":"男","age":15}]
//    版本设置1,运行结果高于版本不会被序列化。其中没有 @Since注解的都会序列化
/*    {"userNameeee":"lailai","age":13}
    [{"userNameeee":"lailai","age":13},{"userNameeee":"yang","age":14},{"userNameeee":"java","age":15}]*/
private static void function3(people people, ArrayList<people> perpleList) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setVersion(1);
        Gson gson = gsonBuilder.create();
        String pStr = gson.toJson(people);
        String plistStr = gson.toJson(perpleList);
        System.out.println(pStr);
        System.out.println(plistStr);
//        反序列化同理
        
        
        
    }
//运行结果:
//    {"userNameeee":"lailai","sexxxx":"男","age":13}
//    [{"userNameeee":"lailai","sexxxx":"男","age":13},{"userNameeee":"yang","sexxxx":"女","age":14},{"userNameeee":"java","sexxxx":"男","age":15}]
//people [userName=lailai, sex=男, age=13]
    //自定义属性序列化后的键
    private static void function2(people people, ArrayList<people> personList) {
        Gson gson = new Gson();
        String pStr = gson.toJson(people);
        String plistStr = gson.toJson(personList);
        System.out.println(pStr);
        System.out.println(plistStr);
//        反序列化
        entity.people peo = gson.fromJson(pStr, people.getClass());
        System.out.println(peo);
    }
/*运行结果:
personStr-----{"userName":"lailai","age":13}
perListStr-----[{"userName":"lailai","age":13},{"userName":"yang","age":14},{"userName":"java","age":15}]
person------Person [userName=null, sex=null, age=13, test=false]
Person [userName=null, sex=null, age=13, test=false]
Person [userName=null, sex=null, age=13, test=false]
Person [userName=null, sex=null, age=13, test=false]*/
//    @Expose注解的使用,可以直接使用new Gson获得gson对象
    private static void function(Person person, ArrayList<Person> personList) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        // 调用excludeFieldsWithoutExposeAnnotation此方法,没有@Expose注解的属性不会被序列化
//        只有这样 Gson 在解析的时候 @Expose 才会生效。
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        Gson gson = gsonBuilder.create();
        String personStr = gson.toJson(person);
        String perListStr = gson.toJson(personList);
        System.out.println("personStr-----" + personStr);
        System.out.println("perListStr-----" + perListStr);
        Person p = gson.fromJson(personStr, Person.class);
        Person[] ps = gson.fromJson(perListStr, Person[].class);
        System.out.println("person------"+p);
        for (Person person2 : ps) {
            System.out.println(p);
        }

    }
}


猜你喜欢

转载自blog.csdn.net/lys1695227550/article/details/79605909