JSON Parsing in android - from resource folder
android, json
Solution
//Get Data From Text Resource File Contains Json Data.
InputStream inputStream = getResources().openRawResource(R.raw.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("Text Data", byteArrayOutputStream.toString());
try {
// Parse the data into jsonobject to get original data in form of json.
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("Categories");
JSONArray jArray = jObjectResult.getJSONArray("Category");
String cat_Id = "";
String cat_name = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
cat_Id = jArray.getJSONObject(i).getString("cat_id");
cat_name = jArray.getJSONObject(i).getString("cat_name");
Log.v("Cat ID", cat_Id);
Log.v("Cat Name", cat_name);
data.add(new String[] { cat_Id, cat_name });
}
} catch (Exception e) {
e.printStackTrace();
}
Problem
I've a kept one text file in res/raw folder in eclipse. I am showing here the content of that file: ``` { "Categories": { "Category": [ { "cat_id": "3", "cat_name": "test" }, { "cat_id": "4", "cat_name": "test1" }, { "cat_id": "5", "cat_name": "test2" }, { "cat_id": "6", "cat_name": "test3" } ] } } ``` I want to parse this JSON array. How can I do this? Can anybody please help me?? Thanks in advance.