GSONJava中很常用的json库,它是google自定义的json库,功能很强大,支持泛型,它也可以实现从json到java对象的装换,也可以从java对象转换成json数据。
导入GSON包
- gardle中加入
bash $ compile 'com.google.code.gson:gson:2.3.1'
- 直接导入jar包
下载地址http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.3.1%7Cjar
### 首先定义一个Peson实体
package com.example.xuyushi.autocompletetext;
/**
* Created by xuyushi on 15/6/22.
*/
public class Person {
public Person() {
super();
}
private String name;
private int age;
private String address;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
class -> json
普通对象
Person person = new Person("zhangsan", 22, "beijing");
Gson gson = new Gson();
String str = gson.toJson(person);
Log.d(TAG, str);
** LOG为**
{"address":"beijing","name":"zhangsan","age":22}
数组对象
List<Person> persons = new ArrayList<Person>();
Person person1 = new Person("zhangsan", 22, "beijing");
Person person2 = new Person("lisi", 23, "shanghai");
Person person3 = new Person("wangwu", 24, "guangzhou");
persons.add(person1);
persons.add(person2);
persons.add(person3);
Gson gson = new Gson();
String str = gson.toJson(persons);
Log.d(TAG, str);
** LOG为**
[{"address":"beijing","name":"zhangsan","age":22},{"address":"shanghai","name":"lisi","age":23},{"address":"guangzhou","name":"wangwu","age":24}]
json -> class
普通对象
Person person = new Person("zhangsan", 22, "beijing");
Gson gson = new Gson();
String str = gson.toJson(person);
// Log.d(TAG, str);
Person personFromJson = gson.fromJson(str, Person.class);
Log.d(TAG, personFromJson.getName());
Log.d(TAG, ""+personFromJson.getAge());
Log.d(TAG, personFromJson.getAddress());
** LOG为**
zhangsan
22
beijing
数组对象(难点)
List<Person> persons = new ArrayList<Person>();
Person person1 = new Person("zhangsan", 22, "beijing");
Person person2 = new Person("lisi", 23, "shanghai");
Person person3 = new Person("wangwu", 24, "guangzhou");
persons.add(person1);
persons.add(person2);
persons.add(person3);
Gson gson = new Gson();
String str = gson.toJson(persons);
// Log.d(TAG, str);
List<Person> personsFromJson = new ArrayList<Person>();
//这里我们通过 Gson中的 TypeToken类是简便操作:这边typeOfT的用法是通过反射机制把T里面的对象的属性的值映射出来,然后通过将json字符串取得的值赋值上去就可以了。
//* getType()的意思就是表示将jsonString的字符串解析出来之后封装到List集合中,然后分别从T里面取出类型将其复制。
personsFromJson = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());
Log.d(TAG, personsFromJson.get(0).getName());
Log.d(TAG, personsFromJson.get(1).getName());
Log.d(TAG, personsFromJson.get(2).getName());
** LOG为**
zhangsan
lisi
wangwu