Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parsing in android - from resource folder

Tags:

json

android

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.

like image 722
Krishna Suthar Avatar asked May 07 '12 09:05

Krishna Suthar


People also ask

Which Library in android will used for JSON parsing?

Android JSONObject is used for JSON parsing in android apps.

Where does android store JSON files?

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.


1 Answers

//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();
}
like image 70
Deval Patel Avatar answered Oct 22 '22 13:10

Deval Patel