android Gson 数组包含不同原子的转化思路

2019-02-26  本文已影响0人  风___________

依赖于JsonElement,通过 JsonElement获取特定字段然后映射为不同的model

解决方案:

private List contentListArrayByKeyValuesArray(String jsonString){
        List modelsArray = new ArrayList();
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(jsonString).getAsJsonArray();
        for (JsonElement jsonObj :array){
            if (jsonObj.getAsJsonObject().get("type").getAsInt() == KapModelContentBase.ARTICLE_TYPE_ARTICLE){
                KapModelContentList model = KapGsonManager.shareGson().fromJson(jsonObj,KapModelContentList.class);
                modelsArray.add(model);
            }
            if (jsonObj.getAsJsonObject().get("type").getAsInt() == KapModelContentBase.ARTICLE_TYPE_BOOK){
                KapModelBookContentList model = KapGsonManager.shareGson().fromJson(jsonObj,KapModelBookContentList.class);
                modelsArray.add(model);
            }
            if (jsonObj.getAsJsonObject().get("type").getAsInt() == KapModelContentBase.ARTICLE_TYPE_MAGZINE){
                KapModelMagzine model = KapGsonManager.shareGson().fromJson(jsonObj,KapModelMagzine.class);
                modelsArray.add(model);
            }
        }
        return modelsArray;
    }

上一篇下一篇

猜你喜欢

热点阅读