改造解封装 JSON 网络服务性能

Retrofit decapsulate JSON webservices performance

我正在使用 Retrofit,我已经创建了实现 TypeAdapterFactoryItemTypeAdapterFactory class 并创建了读取方法...一切都很好,在我的 "response"/"data" (json) 有对象数组.

但是我看它很慢!我有一个 1000/1500 对象数组, 所有的靴子都在我的 ItemTypeAdapterFactory 因为它去了 尽可能多地进入 "read" 方法,并查看 日志,它花了 10-15 秒进入阅读,然后是我的 `recyclerview 充满了数据。

我确定瓶颈在于读取方法被调用的次数与我的数组大小一样多,因为与 POSTMAN 消耗相同的 API,它会在半秒内给我响应。

有没有更快的实现方式?我收到这样使用 google 的回复:

{
  "message": {
     "response": : {
         "myArray": [
            "object 1" : {...},
             ....,
            "object 1500" : {...}
         ]
      },
     "status": "101",
     "statusmessage":"Record is inserted!"
  },
  "kind":"....",
  "etag":" .... "
}

所以我使用 ItemTypeAdapterFactory class 来处理以 JSON 形式出现的响应,并且我对 "message" 中的所有内容进行改造,这是唯一的我感兴趣的东西。

这是在改造中构建 restAdapter 之前调用 ItemTypAdapterFactory 的代码:

Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(new ItemTypeAdapterFactory()) 
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                .create();

我的 ItemTypeAdapterFactory 是这样的:

public class ItemTypeAdapterFactory implements TypeAdapterFactory {

    public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {

            public void write(JsonWriter out, T value) throws IOException {
                delegate.write(out, value);
            }

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    if (jsonObject.has("message") && jsonObject.get("message").isJsonObject()) {
                        jsonElement = jsonObject.get("message");
                    }
                }

                return delegate.fromJsonTree(jsonElement);
            }
        }.nullSafe();
    }
}

如何使用此 AdapterFactory 设置加快改造调用?谢谢!

比这更糟糕的是,您正在为每个元素调用 read,因为您正在为所有类型 return 调用 TypeAdapter。在您的 create 方法中,您应该只为您感兴趣的类型 return 一个新的适配器,而对于其他类型则为 null。来自 TypeAdapterFactory 文档 --

Factories should expect create() to be called on them for many types and should return null for most of those types.

它看起来像 --

public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
    if(type.getType != Item.class) {
        // Do not use custom adapter for other types
        return null;
    }
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>() {
        // your adapter code
    }

看看这个:

Factories should expect create() to be called on them for many types and should return null for most of those types.