Gson操作json

时间:2021-06-20 13:23:14

github:https://github.com/google/gson

API:http://google.github.io/gson/apidocs/

示例对象

 package present;

 public class School {
     private int id;

     public int getId() {
         return id;
     }

     private Address address;

     public Address getAddress() {
         return address;
     }

     public void setAddress(Address address) {
         this.address = address;
     }

     private Student[] students;

     public Student[] getStudents() {
         return students;
     }

     public void setStudents(Student[] students) {
         this.students = students;
     }

     public School(int id) {
         this.id = id;
     }

 }
 package present;

 public class Student {
     private String name;
     private int age;

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

     public int getAge() {
         return this.age;
     }

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

 public class Address {
     private String number;

     private String street;

     public String getStreet() {
         return street;
     }

     public void setStreet(String street) {
         this.street = street;
     }

     public String getNumber() {
         return number;
     }

     public void setNumber(String number) {
         this.number = number;
     }

 }
         School school = new School(10001);
         Address address = new Address();
         address.setNumber("8000");
         address.setStreet("山大路解放街");
         school.setAddress(address);
         Student[] students = new Student[3];
         for (int i = 0; i < students.length; i++) {
             Student student = new Student();
             student.setAge(i + 10);
             student.setName("学生" + i);
             students[i] = student;
         }
         school.setStudents(students);

对象转json串

        Gson gson = new Gson();
        String json = gson.toJson(school);
        System.out.println(json);

Gson操作json

json串转对象

 School result = gson.fromJson(json, School.class);

Gson操作json