安卓大json文件解析_Android-从资产解析巨大(特大)JSON文件的最佳方法

I'm trying to parse some huge JSON file from assets folder. How can i load and add to RecyclerView. would like to know what is the best approch to parse this kind of big file (about 6MB) and if you may know good API that can help me processing this.

解决方案

I recommend you to use the GSON lib. It has very good performance.

Just add this line in your gradle file to import the lib .

compile 'com.google.code.gson:gson:2.2.4'

If your JSON starts with "[" (array of User let's say), you can use GSON like this :

public Set getUsers(final Activity activity) {

Set usersList = new HashSet<>();

String json = readFromAsset(activity, "myfile_with_array.json");

Type listType = new TypeToken>() {}.getType();

// convert json into a list of Users

try {

usersList = new Gson().fromJson(json, listType);

}

catch (Exception e) {

// we never know :)

Log.e("error parsing", e.toString());

}

return usersList;

}

/**

* Read file from asset directory

* @param act current activity

* @param fileName file to read

* @return content of the file, string format

*/

private String readFromAsset(final Activity act, final String fileName)

{

String text = "";

try {

InputStream is = act.getAssets().open(fileName);

int size = is.available();

// Read the entire asset into a local byte buffer.

byte[] buffer = new byte[size];

is.read(buffer);

is.close();

text = new String(buffer, "UTF-8");

} catch (IOException e) {

e.printStackTrace();

}

return text;

}

This will return you a set of Users.

If your JSON Starts with a "{", so can be mapped to an object (User object let's say), you can use it like that :

public User getUser(final Activity activity) {

User user = null;

String json = readFromAsset(activity, "myfile_with_object.json");

try {

// convert json in an User object

user = new Gson.fromJson(json, User.class)

}

catch (Exception e) {

// we never know :)

Log.e("error parsing", e.toString());

}

return user;

}

Hope this helps !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值