天天看點

gson處理泛型的問題

工程裡之前解析網絡請求和做資料緩存都是用的JSONObject,手動解析資料自由度比較高。最近終于受不了一個資料要手動寫半天解析過程了,決定換成用自動解析庫。

現在使用的比較多的一個是谷歌的gson,一個是阿裡的fast-json。網上的資料是說fast-json效率比gson高,但這個庫有一些比較隐藏的坑。反正json解析慢點兒對我沒什麼影響,權衡之下還是打算改用gson。

gson的使用比較簡單,

public class Result {
    @Expose
    private int code;
    @Expose
    private String message;
    @Expose
    private String data;

    private String extra;
}
           

網上找的資料一般說是要寫pojo類,給各個變量加上set、get方法,但經過實際測試并不需要,具體實作沒細看。

處理不想解析的變量有兩種方式:  1. 給要解析的變量加上@Expose注解,然後建立gson時調用GsonBuilder.register.exludeFiledsWithoutExposeAnnotation。2.不解析的變量用transient修飾。

遇到兩個難題:

一個是gson解析泛型的問題,比如工程裡的請求傳回結果都是Result結構的,code和message類型固定,但承載了實際傳回内容的data都是完全不同類型的。由于java的類型擦除問題,我們解析String和ArrayList<String>類型的data可能要這麼做

public Result<String> parseStringResult(Gson gson, Reader reader) {
        return gson.fromJson(reader, new TypeToken<Result<String>>(){}.getType());
    }

    public Result<ArrayList<String>> parseArrayStringResult(Gson gson, Reader reader) {
        return gson.fromJson(reader, new TypeToken<Result<ArrayList<String>>>(){}.getType());
    }
           

但如果要data成為一個泛型,Result定義為:

public class Result<DATA_TYPE> {
    @Expose
    private int code;
    @Expose
    private String message;
    @Expose
    private DATA_TYPE data;

}
           

如果也想用泛型的方式解析Result,用這樣的代碼是不行的:

private <DATA_TYPE> Result<DATA_TYPE> parseResult(Gson gson, Reader reader) {
        return gson.fromJson(reader, new TypeToken<Result<DATA_TYPE>>(){}.getType());
    }
           

DATA_TYPE作為這個函數的泛型,會被直接擦除。可以這麼做:

private <DATA_TYPE> Result<DATA_TYPE> parseResult(Gson gson, Reader reader, final Type typeOfData) {
        Type resultType = new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                return new Type[]{typeOfData};
            }

            @Override
            public Type getOwnerType() {
                return null;
            }

            @Override
            public Type getRawType() {
                return Result.class;
            }
        };
        return gson.fromJson(reader, resultType);
    }
           

DATA_TYPE的類型直接通過Type類型參數傳入,使得最終傳遞給gson的type包含了所有泛型資訊。

之前遇到類型擦除的問題主要還是在于對java的泛型實作不了解,認識到Class和Type的差別之後就明白了。

還有一個棘手的問題就是有的類不好自動解析,比如這種:

{
  "list":[
    {
      "type":"text",
      "text":"this is text"
    },
    {
      "type":"image",
      "image":{
        "image_url":"http://……",
        "width":600,
        "height":400
      }
    },
    {
      "type":"video",
      "video":{
        "thumb_url":"http://……",
        "play_url":"http://……",
        "duration":40000
      }
    }
  ]
}
           

list的子元素可能有不同類型,通過type進行區分,這時list的子元素是要手動解析的,自己實作的解決方案如下:

先定義一個接口IFuzzyDeserializeBean,需要手動解析的資料實作這個接口

public interface IFuzzyDeserializeBean {
    public void deserialize(JsonElement element, JsonDeserializationContext deserializationContext) throws JsonParseException;
}
           

再定義 IFuzzyDeserializeBean接口的解析類,

public class FuzzyBeanDeserializer implements JsonDeserializer<IFuzzyDeserializeBean> {
    @Override
    public IFuzzyDeserializeBean deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        Class c = TypeToken.get(type).getRawType();
        try {
            IFuzzyDeserializeBean bean = (IFuzzyDeserializeBean) c.newInstance();
            bean.deserialize(jsonElement, jsonDeserializationContext);
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
           

将 IFuzzyDeserializeBean的解析類注冊到gson

public class GsonInstance {


    private static ThreadLocal<Gson> gson = new ThreadLocal<Gson>() {
        @Override
        protected Gson initialValue() {
            return new GsonBuilder().registerTypeHierarchyAdapter(IFuzzyTransBean.class, new FuzzyBeanTranser()).
                    registerTypeHierarchyAdapter(FuzzyBeanDeserializer.class, new FuzzyBeanDeserializer()).
                    excludeFieldsWithoutExposeAnnotation().create();
        }
    };

    public static Gson get() {
        return gson.get();
    }
}
           

定義需要手動解析的資料,先取出type進行判斷,然後再通過JsonDesrializationContext完成具體的Image或Video或Text的解析。

public class ListItem implements IFuzzyDeserializeBean{

    private String type;
    private String text;
    private Image image;
    private Video video;

    @Override
    public void deserialize(JsonElement element, JsonDeserializationContext deserializationContext) throws JsonParseException {
        if (!element.isJsonObject()) {
            return;
        }

        JsonObject obj = element.getAsJsonObject();
        JsonElement typeElement = obj.get("type");
        if (null == typeElement || !typeElement.isJsonPrimitive()) {
            return;
        }

        type = typeElement.getAsString();
        JsonElement content;
        switch (type) {
            case "text":
                content = obj.get("text");
                if (null != content && content.isJsonPrimitive()) {
                    text = content.getAsString();
                }
                break;
            case "image":
                content = obj.get("text");
                if (null != content && content.isJsonObject()) {
                    image = deserializationContext.deserialize(content, Image.class);
                }
                break;
            case "video":
                content = obj.get("video");
                if (null != content && content.isJsonObject()) {
                    video = deserializationContext.deserialize(content, Video.class);
                }
                break;
            default:
                break;
        }
    }

    public static class Video {
        @Expose
        private String thumb_url;
        @Expose
        private String play_url;
        @Expose
        private long duration;
    }

    public static class Image {
        @Expose
        private String image_url;
        @Expose
        private int width;
        @Expose
        private int height;
    }
}
           
public class ListData {
    @Expose
    private ArrayList<ListItem> list;
}
           

繼續閱讀