Gson操作json,gsonjson

來源:互聯網
上載者:User

Gson操作json,gsonjson

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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.