Android-从资产解析巨大(特大)JSON文件的最佳方法 [英] Android - Best approach to parse huge (extra large) JSON file from assets

查看:743
本文介绍了Android-从资产解析巨大(特大)JSON文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从资产文件夹中解析一些巨大的JSON文件.我如何加载并添加到RecyclerView.想知道解析这种大文件(大约6MB)的最佳方法是什么,以及您是否知道可以帮助我处理此问题的优质API.

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.

推荐答案

我建议您使用 GSON lib .它具有非常好的性能.

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

只需在gradle文件中添加此行即可导入lib.

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

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

如果您的JSON以"["(假设是用户数组)开头,则可以像这样使用GSON:

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

public Set<User> getUsers(final Activity activity) {

    Set<User> usersList = new HashSet<>();
    String json = readFromAsset(activity, "myfile_with_array.json");
    Type listType = new TypeToken<HashSet<User>>() {}.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.

如果您的JSON以"{"开头,因此可以映射到一个对象(假设是User对象),则可以这样使用它:

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;
    }

希望这会有所帮助!

这篇关于Android-从资产解析巨大(特大)JSON文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆