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 !