public class User {
private String userName;
private int userAge;
private String userEmail;
}
Gson gson = new Gson();
// 序列化
User user = new User("张三", 23, "男");
String jsonUser = gson.toJson(user, User.class);
System.out.println("jsonUser = [" + jsonUser + "]"); // jsonUser = [{"userName":"张三","userAge":23,"userEmail":"男"}]
// 反序列化
User user_ = gson.fromJson(jsonUser, User.class);
System.out.println(user_.toString()); // User{userName='张三', userAge=23, userEmail='男'}
// 序列化数组
String names[] = new String[]{"Teaphy", "Job", "Lous", "Flosd"};
String jsonNames = gson.toJson(names);
System.out.println(jsonNames); // ["Teaphy","Job","Lous","Flosd"]
// 反序列化
String[] strings = gson.fromJson(jsonNames, String[].class);
System.out.println(strings.toString()); //[Teaphy, Job, Lous, Flosd]
// 序列话集合
Type type = new TypeToken>() {
}.getType();
List lists = new ArrayList<>();
lists.add(new User("Jso", 23, "M"));
lists.add(new User("Taad", 45, "W"));
lists.add(new User("Goos", 23, "M"));
String jsonList = gson.toJson(lists, type);
System.out.println(jsonList); // [{"userName":"Jso","userAge":23,"userEmail":"M"},
// {"userName":"Taad","userAge":45,"userEmail":"W"},
// {"userName":"Goos","userAge":23,"userEmail":"M"}]
// 反序列化集合
List lists_ = gson.fromJson(jsonList, type);
System.out.println(lists_.toString()); // [User{userName='Jso', userAge=23, userEmail='M'},
// User{userName='Taad', userAge=45, userEmail='W'},
// User{userName='Goos', userAge=23, userEmail='M'}]
{
"retCode": "0000",
"resInfo": "成功",
"User":{
"userName":"张三",
"userAge":23,
"userEmail":"[email protected]"
}
}
2.1 封装Result<>泛型类
public class Result {
public int code;
public String message;
public T data;
}
2. 解析
{"retCode": "0000","resInfo": "成功","User":{ ...}}
{"retCode": "0000","resInfo": "成功","Users":{ {...}...}}
* 没有引入泛型以前
public class UserResult {
public int code;
public String message;
public User data;
}
//=========
public class UserListResult {
public int code;
public String message;
public List data;
}
//=========
String json = "{..........}";
Gson gson = new Gson();
UserResult userResult = gson.fromJson(json,UserResult.class);
User user = userResult.data;
UserListResult userListResult = gson.fromJson(json,UserListResult.class);
List users = userListResult.data;
解析时,针对不同的情况,总是要写一不同的接口。
* 引入泛型以后
//不再重复定义Result类
Type userType = new TypeToken>(){}.getType();
Result userResult = gson.fromJson(json,userType);
User user = userResult.data;
Type userListType = new TypeToken>>(){}.getType();
Result> userListResult = gson.fromJson(json,userListType);
List users = userListResult.data;
引入泛型以后,只需要一个接口,即可解析。
Gson博大精深,还需继续领悟啊!!!
参考资料:
1.Gson使用细节