在讲如何解析数据之前,先描述一下gson中的两个注解@Expose和@SerializedName。
@Expose注解的作用:区分实体中不想被序列化的属性,其自身包含两个属性deserialize(反序列化)和serialize(序列化),默认都为true。
使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();创建Gson对象,没有@Expose注释的属性将不会被序列化.。
private class User{
private int id;
@Expose
private String name;
.......
}
这样create() gson对象序列化user,只会有name这一个属性
@SerializedName注解的作用:定义属性序列化后的名称
public class User{
private int id;
@Expose
@SerializedName("username")
private String name;
.......
}
另外想要不序列化某个属性,也可以使用transient。
private class User{
private int id;
private transient String name;
.......
}
下面列举一下gson如何解析json数据的
//转换器
GsonBuilder builder = new GsonBuilder();
// 不转换没有 @Expose 注解的字段
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
//1、对象转string
Student stu = new Student();
stu.setStudentId(333);
stu.setStudentName("qqq");
String stuStr = gson.toJson(stu);
System.out.println(stuStr); //{"studentName":"qqq","studentId":333}
//2、string转对象
Student user2 = gson.fromJson(stuStr, Student.class);
System.out.println(user2);
String stuTemp = "{\"studentName\":\"qqq2\",\"studentId\":3335}";
Student user4 = gson.fromJson(stuTemp, Student.class);
System.out.println(user4);
//3、对象List转string
List testBeanList = new ArrayList();
Student testBean = new Student();
testBean.setStudentId(555);
testBean.setStudentName("552");
testBeanList.add(testBean);
//Gson gsonList = new Gson();
Type type = new TypeToken>(){}.getType(); //指定集合对象属性
String beanListToJson = gson.toJson(testBeanList, type);
System.out.println(beanListToJson); //[{"studentName":"552","studentId":555}]
//集合string转对象list
List testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson); //[555:552]
//4、集合如果不指定类型 默认为String
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson); //["first","second"]
//5、集合字符串转回来需要指定类型
List testList2 = (List) gson.fromJson(listToJson,new TypeToken>() {}.getType());
System.out.println(testList2);
//6、 将HashMap字符串转换为 JSON
Map testMap = new HashMap();
testMap.put("id", "id.first");
testMap.put("name", "name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson); //{"id":"id.first","name":"name.second"}
//7、stringMap转对象
Map userMap2 = (Map) gson.fromJson(mapToJson,new TypeToken