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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/fumier/article/details/48443469

在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


展开阅读全文

没有更多推荐了,返回首页