Gson的日常用法
阿新 • • 發佈:2019-01-09
其他相關的資料百度,各大部落格論壇都有 我就不一一抄襲總結了..
- 簡單物件轉換
Obj obj = new Gson().fromJson(json,Obj .class);
- List簡單物件轉換
List<Obj> objList = new Gson().fromJson(json,new TypeToken<List<Obj>>(){}.getType());
- GsonBuilder物件使用
- //注意這裡的Gson的構建方式為GsonBuilder,區別於test1中的Gson gson = new Gson();
- Gson gson = new GsonBuilder()
- .excludeFieldsWithoutExposeAnnotation() //不匯出實體中沒有用@Expose註解的屬性
- .enableComplexMapKeySerialization() //支援Map的key為複雜物件的形式
- .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//時間轉化為特定格式
- .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//會把欄位首字母大寫,注:對於實體上使用了@SerializedName註解的不會生效.
- .setPrettyPrinting() //對json結果格式化.
- .setVersion(1.0) //有的欄位不是一開始就有的,會隨著版本的升級新增進來,那麼在進行序列化和返序列化的時候就會根據版本號來選擇是否要序列化.
- //@Since(版本號)能完美地實現這個功能.還的欄位可能,隨著版本的升級而刪除,那麼
- //@Until(版本號)也能實現這個功能,GsonBuilder.setVersion(double)方法需要呼叫.
- .create();
- Gson註解(應該還有很多)
- private int id; //不匯出
- @Expose //輸出json欄位 不指定Name
- private String name;
- @Expose
- @SerializedName("bir") //重新指定 匯出欄位為bir
- private Date birthDay;
- Map的處理(簡單物件)
- Map<Point, String> map1 = new LinkedHashMap<Point, String>();// 使用LinkedHashMap將結果按先進先出順序排列
- map1.put(new Point(5, 6), "a");
- map1.put(new Point(8, 8), "b");
- String s = gson.toJson(map1);
- System.out.println(s);// 結果:[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]
- Map<Point, String> retMap = gson.fromJson(s,
- new TypeToken<Map<Point, String>>() {
- }.getType());
- for (Point p : retMap.keySet()) {
- System.out.println("key:" + p + " values:" + retMap.get(p));
- }
- System.out.println(retMap);
- Map的複雜物件處理
- Map<String, Object> map = new LinkedHashMap<String, Object>();
- map.put("students", stulist);
- map.put("teachers", teacherList);
- Gson gson = new Gson();
- String s = gson.toJson(map);
- System.out.println(s);
- System.out.println("----------------------------------");
- Map<String, Object> retMap = gson.fromJson(s,
- new TypeToken<Map<String, List<Object>>>() {
- }.getType());
- 實際開發中的特殊需求處理
[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹貴生","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:54:49 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老師","title":"教授"},{"id":2,"name":"丁老師","title":"講師"}]}]
- public class Student {
- private int id;
- private String name;
- private Date birthDay;
- }
- public class Teacher {
- private int id;
- private String name;
- private String title;
- }
- public class TableData {
- private String tableName;
- private List tableData;
- }
- // 將json轉為資料-->start
- List<TableData> tableDatas2 = gson.fromJson(s,
- new TypeToken<List<TableData>>() {
- }.getType());
- for (int i = 0; i < tableDatas2.size(); i++) {
- TableData entityData = tableDatas2.get(i);
- String tableName = entityData.getTableName();
- List tableData = entityData.getTableData();
- String s2 = gson.toJson(tableData);
- // System.out.println(s2);
- // System.out.println(entityData.getData());
- if (tableName.equals("students")) {
- System.out.println("students");
- List<Student> retStuList = gson.fromJson(s2,
- new TypeToken<List<Student>>() {
- }.getType());
- for (int j = 0; j < retStuList.size(); j++) {
- System.out.println(retStuList.get(j));
- }
- } else if (tableName.equals("teachers")) {
- System.out.println("teachers");
- List<Teacher> retTchrList = gson.fromJson(s2,
- new TypeToken<List<Teacher>>() {
- }.getType());
- for (int j = 0; j < retTchrList.size(); j++) {
- System.out.println(retTchrList.get(j));
- }
- }
- }
- // Json轉為物件-->end
- 註冊TypeAdapter以及處理Enum型別
- public enum PackageState {
- PLAY, UPDATE, UPDATING, DOWNLOAD, DOWNLOADING,
- }
- public class PackageItem {
- private String name;
- private PackageState state;
- private String size;
自己寫一個轉換器實現JsonSerializer<T>介面和jsonDeserializer<T>介面:
- public class EnumSerializer implements JsonSerializer<PackageState>,
- JsonDeserializer<PackageState> {
- // 物件轉為Json時呼叫,實現JsonSerializer<PackageState>介面
- @Override
- public JsonElement serialize(PackageState state, Type arg1,
- JsonSerializationContext arg2) {
- return new JsonPrimitive(state.ordinal());
- }
- // json轉為物件時呼叫,實現JsonDeserializer<PackageState>介面
- @Override
- public PackageState deserialize(JsonElement json, Type typeOfT,
- JsonDeserializationContext context) throws JsonParseException {
- if (json.getAsInt() < PackageState.values().length)
- return PackageState.values()[json.getAsInt()];
- return null;
- }
- }
- public static void main(String[] args) {
- GsonBuilder gsonBuilder = new GsonBuilder();
- gsonBuilder.registerTypeAdapter(PackageState.class,
- new EnumSerializer());
- Gson gson = gsonBuilder.create();
- PackageItem item = new PackageItem();
- item.setName("item_name");
- item.setSize("500M");
- item.setState(PackageState.UPDATING);// 這個 state是列舉值
- String s = gson.toJson(item);
- System.out.println(s);
- System.out.println("--------------------------------");
- PackageItem retItem = gson.fromJson(s, PackageItem.class);
- System.out.println(retItem);
- }