Gson(又称Google Gson)是Google公司发布的一个开放源码的Java库,主要用途为序列化Java对象为JSON字串,或反序列化JSON字串成Java对象。
/** * java对象转化为json字符串 */
private void objToJson(){
User user = new User();
user.setAge(13);
user.setHeight(17.1f);
user.setName("张三");
Gson gson = new Gson();
String json = gson.toJson(user);
Log.d(GSON_TEST,json);
// {"name":"张三","height":17.1,"age":13}
}
/** * json字符串转化为java对象 */
private void jsonToObj(){
String json = "{\"name\":\"张三\",\"height\":17.1,\"age\":13}";
Gson gson = new Gson();
User user = gson.fromJson(json,User.class);
Log.d(GSON_TEST,user.toString());
// name : 张三,age : 13, height : 17.1
}
/**
* json数组转化为java对象集合
*/
private void jsonArrayToObjArray(){
String json = "[{\"name\":\"张三\",\"height\":17.1,\"age\":13}" +
",{\"name\":\"李四\",\"height\":18.1,\"age\":14}" +
",{\"name\":\"王五\",\"height\":17.5,\"age\":23}" +
",{\"name\":\"赵六\",\"height\":16.7,\"age\":31}]";
Gson gson = new Gson();
TypeToken<List<User>> typeToken = new TypeToken<List<User>>(){};
List<User> userList = gson.fromJson(json,typeToken.getType());
Log.d(GSON_TEST,userList.toString());
/**
[name : 张三,age : 13, height : 17.1, name : 李四,age : 14, height : 18.1, name : 王五,age : 23, height : 17.5, name : 赵六,age : 31, height : 16.7]
*/
}
/**
* json数据转化为java对象map集合
*/
private void jsonArrayToObjMap(){
String json = "{\"one\":{\"name\":\"张三\",\"height\":17.1,\"age\":13}" +
",\"two\":{\"name\":\"李四\",\"height\":18.1,\"age\":14}" +
",\"three\":{\"name\":\"王五\",\"height\":17.5,\"age\":23}" +
",\"four\":{\"name\":\"赵六\",\"height\":16.7,\"age\":31}}";
Gson gson = new Gson();
TypeToken<Map<String,User>> typeToken = new TypeToken<Map<String,User>>(){};
Map<String,User> userList = gson.fromJson(json,typeToken.getType());
Log.d(GSON_TEST,userList.toString());
//{one=name : 张三,age : 13, height : 17.1, two=name : 李四,age : 14, height : 18.1, three=name : 王五,age : 23, height : 17.5, four=name : 赵六,age : 31, height : 16.7}
}
/**
* 多层嵌套的json数据转化为多层Java对象
*/
private void jsonLayerToObjLayer(){
String json = "{\"works\":[{\"name\":\"张三\",\"height\":17.1,\"age\":13}" +
",{\"name\":\"张三\",\"height\":17.1,\"age\":13}" +
",{\"name\":\"张三\",\"height\":17.1,\"age\":13}]}";
Gson gson = new Gson();
User user = gson.fromJson(json,User.class);
Log.d(GSON_TEST,user.getWorks().toString());
// [name : 张三,age : 13, height : 17.1, name : 张三,age : 13, height : 17.1, name : 张三,age : 13, height : 17.1]
}
对象结构
public class User {
private String name;
private int age;
private float height;
private List<Work> works;
}
public class Work {
private String name;
private int age;
private float height;
}
站在巨人的肩膀上,我们才能看的更远