简体   繁体   中英

Read JSON file from assets

I am trying to read a JSON file from assets in fragment using getAssets() , but the IDE says "can not resolve this method (getAssets())".

Code

 public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getAssets().open("moods.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;

}

Try this:

Create a class LoaderHelper.java

public class LoaderHelper {
    public static String getJson(Context context, String json){
        String jsonString=parseFileToString(context, json);
        return jsonString;
    }
    public static String parseFileToString( Context context, String filename )
    {
        try
        {
            InputStream stream = context.getAssets().open( filename );
            int size = stream.available();

            byte[] bytes = new byte[size];
            stream.read(bytes);
            stream.close();

            return new String( bytes );

        } catch ( IOException e ) {
            Log.i("GuiFormData", "IOException: " + e.getMessage() );
        }
        return null;
    }
}

To get the json string call the above class as:

String str=LoaderHelper.parseFileToString(context, "levels.json");

where levels.json is the json file stored in asset folder.

Method getAssets() is part of Context class. So if you're not calling loadJSONFromAsset() in the class that extends Context, eg Activity, you need to provide reference to Context as an argument to your method and then call getAssets() on it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM