你的位置:首页 > Java教程

[Java教程]Gson操作json

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

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

示例对象

 1 package present; 2  3 public class School { 4   private int id; 5  6   public int getId() { 7     return id; 8   } 9 10   private Address address;11 12   public Address getAddress() {13     return address;14   }15 16   public void setAddress(Address address) {17     this.address = address;18   }19 20   private Student[] students;21 22   public Student[] getStudents() {23     return students;24   }25 26   public void setStudents(Student[] students) {27     this.students = students;28   }29 30   public School(int id) {31     this.id = id;32   }33 34 }

View Code
 1 package present; 2  3 public class Student { 4   private String name; 5   private int age; 6    7   public String getName() { 8     return name; 9   }10   public void setName(String name) {11     this.name=name;12   }13   14   public int getAge() {15     return this.age;16   }17   18   public void setAge(int age) {19     this.age=age;20   }21 }

View Code
 1 package present; 2  3 public class Address { 4   private String number; 5    6   private String street; 7  8   public String getStreet() { 9     return street;10   }11 12   public void setStreet(String street) {13     this.street = street;14   }15 16   public String getNumber() {17     return number;18   }19 20   public void setNumber(String number) {21     this.number = number;22   }23 24 }

View Code
 1     School school = new School(10001); 2     Address address = new Address(); 3     address.setNumber("8000"); 4     address.setStreet("山大路解放街"); 5     school.setAddress(address); 6     Student[] students = new Student[3]; 7     for (int i = 0; i < students.length; i++) { 8       Student student = new Student(); 9       student.setAge(i + 10);10       student.setName("学生" + i);11       students[i] = student;12     }13     school.setStudents(students);

View Code

对象转json串

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

json串转对象

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