從我的Android應用程序中,我需要使用RESTful Web服務,該服務返回json格式的對象列表。 這個列表可能很長(大約1000/2000對象)。Android應用程序中JSON對象綁定的替代方案
我需要做的是搜索和檢索json文件中的一些對象。
由於移動設備的內存有限,我一直在考慮使用對象綁定(例如使用GSON庫)會有危險。
哪些是解決這個問題的替代方案?
從我的Android應用程序中,我需要使用RESTful Web服務,該服務返回json格式的對象列表。 這個列表可能很長(大約1000/2000對象)。Android應用程序中JSON對象綁定的替代方案
我需要做的是搜索和檢索json文件中的一些對象。
由於移動設備的內存有限,我一直在考慮使用對象綁定(例如使用GSON庫)會有危險。
哪些是解決這個問題的替代方案?
If you are using gson, use gson streaming。
我從鏈接添加的樣品,並加入我的評論在它的內部:
public List<Message> readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
Message message = gson.fromJson(reader, Message.class);
// TODO : write an if statement
if(someCase) {
messages.add(message);
// if you want to use less memory, don't add the objects into an array.
// write them to the disk (i.e. use sql lite, shared preferences or a file...) and
// and retrieve them when you need.
}
}
reader.endArray();
reader.close();
return messages;
}
例如
1)閱讀列表作爲流和處理上飛單JSON實體只保存那些你感興趣的
2)將數據讀入String對象/對象,然後找到JSON實體並逐一處理它們,而不是同時處理所有事物。分析JSON結構字符串的方法包括正則表達式或手動indexOf與子字符串類型分析相結合。
1)效率更高,但需要更多的工作,因爲您必須同時處理流,其中2)可能更簡單,但它需要您使用相當大的字符串作爲臨時手段。
很好的答案!這正是我所期待的。謝謝 :) – GVillani82 2014-11-02 12:06:19