【发布时间】:2015-10-05 08:43:23
【问题描述】:
我正在使用 Retrofit,我创建了实现 TypeAdapterFactory 的 ItemTypeAdapterFactory 类并创建了 read 方法......并且在我的“响应”/“数据”(json) 中一切正常有一个对象数组。
但我可以看到它很慢!我有一个 1000/1500 对象的数组,
所有的靴子都在我的ItemTypeAdapterFactory,因为它去了
尽可能多地进入“读取”方法,并查看
记录,它会花 10-15 秒的时间阅读,然后我的
`recyclerview 填充数据。
我确定瓶颈在 read 方法中被调用的次数与我的数组大小一样多,因为使用 POSTMAN 使用相同的 API,它会在半秒内给我响应。
有没有更快的实现方法?我收到这样的使用 google 的回复:
{
"message": {
"response": : {
"myArray": [
"object 1" : {...},
....,
"object 1500" : {...}
]
},
"status": "101",
"statusmessage":"Record is inserted!"
},
"kind":"....",
"etag":" .... "
}
所以我使用 ItemTypeAdapterFactory 类来处理完全以 JSON 形式出现的响应,并且我通过改造“消息”中的所有内容来获得这是我唯一感兴趣的内容。
这是在改造中构建 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 设置更快地进行改造调用?谢谢!
【问题讨论】:
-
如下所述解决
标签: android json performance gson retrofit