简体   繁体   中英

Trying to load json from assets in android studio

Here is my code:

public String loadJSONFromAsset() {
    String json = null;
    try {

        InputStream is = getAssets().open("index.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;

}

JSONObject object = new JSONObject(loadJSONFromAsset());

I get an error underlining the last row:

JSONObject object = new JSONObject(loadJSONFromAsset());

saying:

Unhandled Exception org.json.JSONException

You wrapped all your InputStream operations in a try block catching IOException . What the error is telling you is that you need to wrap that last line in a try block that catches JSONException .

You can use a different try block, but better design is to use the same try block, put that statement inside the block and catch JSONException as well as IOException in that block. Then have your method return a JSONObject rather than a String .

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