2011年12月22日 星期四

Load Large Json On Android

Gson
https://sites.google.com/site/gson/Home

Tutorial:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

在 Android 上如果要讀一個非常大的Json:5000筆、10000筆之類的。
直接讀成 String 一定會讓記憶體爆掉的。
這時候就要用Gson啦~
Tutorial是讀一個Obj,下面範例是讀一個Array。

Sample Data Foamat:


[{"num":"110013"},{"num":"110014"},{"num":"110015"}]

Class:


import com.google.gson.annotations.SerializedName;

public class Store {
@SerializedName("num")
public String num;
}

Sample Code:


InputStream is = YOUR_DATA

Gson gson = new Gson();
Reader reader = new InputStreamReader(is);
Type collectionType = new TypeToken<List<Store>>(){}.getType();
List<Store> stores = gson.fromJson(reader, collectionType);
for(Store store : stores) {
Log.d("GSON", "update:" + store.num);
}

沒有留言:

張貼留言