Using JSON File in Android App Resources

前端 未结 8 1140
盖世英雄少女心
盖世英雄少女心 2020-11-28 21:00

Suppose I have a file with JSON contents in the raw resources folder in my app. How can I read this into the app, so that I can parse the JSON?

相关标签:
8条回答
  • 2020-11-28 21:22

    From http://developer.android.com/guide/topics/resources/providing-resources.html:

    raw/
    Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.

    However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ are not given a resource ID, so you can read them only using AssetManager.

    0 讨论(0)
  • 2020-11-28 21:29

    Like @mah states, the Android documentation (https://developer.android.com/guide/topics/resources/providing-resources.html) says that json files may be saved in the /raw directory under the /res (resources) directory in your project, for example:

    MyProject/
      src/ 
        MyActivity.java
      res/
        drawable/ 
            graphic.png
        layout/ 
            main.xml
            info.xml
        mipmap/ 
            icon.png
        values/ 
            strings.xml
        raw/
            myjsonfile.json
    

    Inside an Activity, the json file can be accessed through the R (Resources) class, and read to a String:

    Context context = this;
    Inputstream inputStream = context.getResources().openRawResource(R.raw.myjsonfile);
    String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();
    

    This uses the Java class Scanner, leading to less lines of code than some other methods of reading a simple text / json file. The delimiter pattern \A means 'the beginning of the input'. .next() reads the next token, which is the whole file in this case.

    There are multiple ways to parse the resulting json string:

    • Use the Java / Android built in JSONObject and JSONArray objects, like here: JSON Array iteration in Android/Java. It may be convenient to get Strings, Integers etc. using the optString(String name), optInt(String name) etc. methods, not the getString(String name), getInt(String name) methods, because the opt methods return null instead of an exception in case of failing.
    • Use a Java / Android json serializing / deserializing library like the ones mentiod here: https://medium.com/@IlyaEremin/android-json-parsers-comparison-2017-8b5221721e31
    0 讨论(0)
提交回复
热议问题