記·處理服務端返回data不統一處理

505951628@qq.com發表於2018-01-25
伺服器返回data列表有資料時:
{
    "code":0,
    "message":"操作成功",
    "data":[],
}

伺服器返回data列表沒有資料時:
{
    "code":0,
    "message":"操作成功",
    "data":{},
}

新建類JsonDeserializerList 實現 JsonDeserializer
public class JsonDeserializerList implements JsonDeserializer<List<?>> {
    @Override
    public List<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonArray()) {
            JsonArray array = json.getAsJsonArray();
            Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
            List list = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JsonElement element = array.get(i);
                Object item = context.deserialize(element, itemType);
                list.add(item);
            }
            return list;
        } else {
            return Collections.EMPTY_LIST;
        }
    }
}
註冊:
gsonBuilder.registerTypeHierarchyAdapter(List.class, new JsonDeserializerList()).create();
複製程式碼

相關文章