Reading a json file in Android

AndroidJson

Android Problem Overview


I have the following json file. I want to know where should i place the json file in my project and how to read and store it.

{
"aakash": [
	[  0.070020,0.400684],
	[  0.134198,0.515837],
	[  0.393489,0.731809],
	[  0.281616,0.739490]
	
],
"anuj": [
	[  1287.836667,-22.104523],
	[  -22.104523,308.689613],
	[  775.712801,-13.047385],
	[  -13.047385,200.067743]
]
}

Android Solutions


Solution 1 - Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
		String json = null;
		try {
			InputStream is = context.getAssets().open("file_name.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;

	}

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAakash AnujView Question on Stackoverflow
Solution 1 - AndroidFaizanView Answer on Stackoverflow