Retrofit中使用GSON解析定製格式的JSON

在Retrofit中默認使用GSON解析JSON數據。使用GSON將json轉換爲POJO對象。它默認的解析格式是這樣的:

{
  "login": "basil2style",
  "id": 1285344,
  "avatar_url": "https://avatars.githubusercontent.com/u/1285344?v=3",
  "gravatar_id": "123"}

那如果JSON數據是如下內容時,該怎麼去解析呢?

{"data":[{"id":1,"divisionStr":"北京","name":"北京","lng":116.39564514160156,"lat":39.92998504638672,"pinyin":"beijing"},{"id":10,"divisionStr":"","name":"上海","lng":121.48789978027344,"lat":31.249162673950195,"pinyin":"shanghai"},{"id":20,"divisionStr":"","name":"廣州","lng":113.30764770507812,"lat":23.12004852294922,"pinyin":"guangzhou"},{"id":30,"divisionStr":"","name":"深圳","lng":114.02597045898438,"lat":22.54605484008789,"pinyin":"shenzhen"}}
我們想把data所對應的值中的每一項取出來,然後轉換成一個個的對象。

這時候我們需要使用GsonBuilder去重新定義json數據的解析方式。

GSON提供了TypeAdapter,可以在TypeAdapterFactory中定義解析邏輯。而該題中,我只需要獲得data所對應得值即可,即數組對象。

private static class ItemTypeAdapterFactory implements TypeAdapterFactory {
       
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
            final TypeAdapter<JsonElement> elementTypeAdapter = gson.getAdapter(JsonElement.class);


            return new TypeAdapter<T>() {
                @Override
                public void write(JsonWriter out, T value) throws IOException {
                    delegate.write(out, value);
                }
                //當獲取了http請求的數據後,獲得data所對應的值
                @Override
                public T read(JsonReader in) throws IOException {
                    JsonElement jsonElement = elementTypeAdapter.read(in);
                    if (jsonElement.isJsonObject()) {
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.has("data")) {
                            jsonElement = jsonObject.get("data");
                        }
                    }

                    return delegate.fromJsonTree(jsonElement);
                }

            }.nullSafe();
        }
    }

參考鏈接:http://stackoverflow.com/questions/30114793/adapting-retrofit-responses-using-gson

                  https://github.com/rciovati/retrofit-loaders-example

                  http://blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/

                  http://stackoverflow.com/questions/21811999/best-practice-to-implement-retrofit-callback-to-recreated-activity


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章