标签:android
Gson gson = new Gson(); /*Gson的fromJson方法是在和Bean的属性努力的对应。*/ String str = "{\"age\":20}"; Person bean = gson.fromJson(str, Person.class); System.out.println(str); System.out.println(bean.toString()); // 输出: // {"age":20} // Person [name=null, age=20] //=========================================================================== Person p = new Person("ldd",20); Student s = new Student("xll",23,p); String str1 = gson.toJson(s); System.out.println(str1); // 输出: // { // "name": "xll", // "age": 23, // "person": { // "name": "ldd", // "age": 20 // } // } //============================================================================ Student stu1 = gson.fromJson(str1, Student.class); System.out.println(stu1.toString()); // 输出: //Student [name=xll, age=23, person=Person [name=ldd, age=20]] //============================================================================= Type listType = new TypeToken<List<Person>>() {}.getType(); List<Person> persons = new ArrayList<Person>(); for (int i = 0; i < 4; i++) { Person pp = new Person(); pp.setName("name" + i); pp.setAge(i * 5); persons.add(pp); } String str3 = gson.toJson(persons,listType); System.out.println(str3); /* [ { "name": "name3", "age": 15 }, { "name": "name3", "age": 15 }, { "name": "name3", "age": 15 }, { "name": "name3", "age": 15 } ]*/ //=================================================================== List<Person> listPerson = gson.fromJson(str3, listType); System.out.println(listPerson.toString()); // 输出: //[Person [name=name0, age=0], Person [name=name1, age=5], Person [name=name2, age=10], Person [name=name3, age=15]]
<pre name="code" class="java">package com.panpass.main; public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
<pre name="code" class="java">package com.panpass.main; public class Student { private String name; private int age; private Person person; public Student(String name, int age, Person person) { super(); this.name = name; this.age = age; this.person = person; } public Student() { super(); // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", person=" + person + "]"; } }
标签:android
原文地址:http://blog.csdn.net/soulofandroid/article/details/42524387