简体   繁体   中英

Load External JSON file in Java Android

i just started learning Java. I'm currently working on a small app that retrieves data from a .JSON file, and stores it into a SQLite database.

I'm trying to open a . JSON file and store it as a JSONObject . Here is my code for reading a JSON file.

private JSONObject readFile(String path) {
    StringBuilder sb = new StringBuilder();
    try {
        FileReader in = new FileReader(new File(path));
        int b;
        while((b = in.read()) != -1) {
            sb.appendCodePoint(b);
        }
        in.close();

        return new JSONObject(sb.toString());
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

My JSON files are stored in : app\\src\\main\\java\\proj\\bb\\database\\jsonFiles Im currently calling the readFile method like this:, but it throws a NullPointer . (DatabaseOperations is the classname).

JSONObject jsonFile = readFile(DatabaseOperations.class.getResource("filename.json").toString());
JSONArray arr = jsonFile.getJSONArray("someArray");

I also tried this without succes:

JSONObject jsonFile = readFile("jsonFiles/filename.json").toString());
JSONArray arr = jsonFile.getJSONArray("someArray");

So my question is, what needs to be the path i need to pass as an argument? Or am I doing something else wrong?

Thanks in advance !

Put your JSON Files in the assets folder and access it from there. You can use the following method to read the data as-

public static String getJSONData(Context context, String textFileName) {
    String strJSON;
    StringBuilder buf = new StringBuilder();
    InputStream json;
    try {
        json = context.getAssets().open(textFileName);

        BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));

        while ((strJSON = in.readLine()) != null) {
            buf.append(strJSON);
        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return buf.toString();
}

Method will return the JSON string and you can create instance of JSONObject as

External json file as : sample.json

String jsonString = getJSONData(MainActivity.this, "sample.json");

JSONObject jsonObject = new JSONObject(jsonString);

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