Using JSON File in Android App Resources

Using JSON File in Android App Resources

See openRawResource. Something like this should work:

InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}

String jsonString = writer.toString();

Reading JSON or text file in resource folder

If you want to read a file from res/raw folder you can obtain InputStream by R.raw.yourfile id like this:

resources.openRawResource(R.raw.yourfile)

Or you can open file by Uri:

val uri = Uri.parse("android.resource://com.example.your_package/raw/yourfile")
val file = File(uri.getPath());

Alternatevily you can put your files in assets/ folder and get InputStream like this:

assets.open("yourfile.txt")

how to add json file to android project

I want to simply move it over under app

If you literally mean that you want to have app/something.json, you are welcome to put the file there, but it will not be packaged with your app, and it will not be available to you at runtime.

If you want to ship the JSON with your app, you have four major options:

  • Put it in assets/ and read it in using AssetManager and its open() method to get an InputStream

  • Put it in res/raw/ and read it in using Resources and its openRawResource() method

  • Hardcode it as a string in Java code

  • Write yourself a code generator that converts JSON into a Java class that you would access like you do the code-generated R and BuildConfig classes

It is possible that such a code generator already exists. I have a rudimentary Gradle plugin that does this, as an example that I'll be including in the next update of my book.

Using local json file in Android

There are so many ways,

  • You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778

  • You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778

For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html

For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/



Related Topics



Leave a reply



Submit