数据解析(二):Gson解析

一.Gson通常的用法有四种

 1.把java对象转换成json字符串(序列化) 
  

  public void JavaToJson() {
        Student stu = new Student("李毅", 23);
        Gson gson = new Gson();
        String s = gson.toJson(stu);
        System.out.println("javaToJSon:" + s);
        //I/System.out: javaToJSon:{"name":"李毅","age":23}
    }


2.把集合对象转换成json字符串(序列化)

 public void ListToJson() {
        ArrayList data = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Student stu = new Student("N" + i, i);
            data.add(stu);
        }
        Gson gson = new Gson();
        String s = gson.toJson(data);
        System.out.println("listToJSON:" + s);
        //System.out: listToJSON:[{"name":"N0","age":0},{"name":"N1","age":1},{"name":"N2","age":2}]
    }


3.把json字符串转换成javaBean对象(反序列化)

public void jsonToJava() {
        Student stu = new Student("李毅", 23);
        Gson gson = new Gson();
        String json = gson.toJson(stu);
        Student student = gson.fromJson(json, Student.class);
        System.out.println("jsonToJava:" + student.toString());
        //I/System.out: listToJSON:[{"name":"N0","age":0},{"name":"N1","age":1},{"name":"N2","age":2}]
    }


4.把json字符串转换成集合对象(反序列化)

  public void JsonToList() {
        ArrayList data = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Student stu = new Student("N" + i, i);
            data.add(stu);
        }
        Gson gson = new Gson();
        String json = gson.toJson(data);
        ArrayList coll = gson.fromJson(json, new TypeToken>() {
        }.getType());
        System.out.println("jsonToList:" + coll.size());
        // I/System.out: jsonToList:3




你可能感兴趣的:(数据解析)