Reputation: 124
I want to parse a json file into my Android app. But the json file is going to be into my project folder. I tried to connect a json url and parse that way.
All the sample codes on the internet makes a communication with internet to parse json data. By this way i want to get rid of httpPost, Service Handler class and things like that which provides communication with internet. I think this way it will be easier. How can i do that? Any suggesting link? And will you agree with me about being easy? Am i right?
Thanks in advance.
Upvotes: 0
Views: 522
Reputation: 746
Create a folder named "raw" or whatever name you'd like inside your android project's res directory. Create a new file inside this folder, let's call this "raw_file.json". You can parse this JSON file into your Android app by doing the below:
try {
InputStream inputStream = getResources().openRawResource(R.raw.raw_file);
byte[] b = new byte[inputStream.available()];
inputStream.read(b);
JSONObject jsonObject = new JSONObject(new String(b));
String s = jsonObject.getString("someKey");
} catch (JSONException e) {
Log.e(TAG, e.toString());
} catch (IOException e){
Log.e(TAG, e.toString());
}
Upvotes: 3
Reputation: 93561
Put it in your assets folder, then read the file in from assets. Parse the resulting string. Its fairly common code.
Upvotes: 1