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?
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.
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:
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.