14

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Krishna Suthar
  • 3,071
  • 6
  • 31
  • 37
  • possible duplicate of [How to parse json string in Android?](http://stackoverflow.com/questions/8091051/how-to-parse-json-string-in-android) – Felix Kling May 07 '12 at 09:04
  • Please tell me. how can I write this data in string?? Help me – Krishna Suthar May 07 '12 at 09:06
  • @KrishnaSuthar How about using a dedicated library for parsing the JSON such as [Gson](https://code.google.com/p/google-gson/) or [Jackson](https://github.com/FasterXML/jackson)? Also [Apache Commons](http://commons.apache.org/proper/commons-io/) might be worth a look for reading the input stream with `IOUtils`. – JJD Oct 08 '13 at 14:42

4 Answers4

41
//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();
}
JJD
  • 50,076
  • 60
  • 203
  • 339
Deval Patel
  • 780
  • 7
  • 18
2

This is your code:

String fileContent;
            JSONObject jobj = new JSONObject(fileContent);
            JSONObject categories = jobj.getJSONObject("Categories");
            JSONArray listCategory = categories.getJSONArray("Category");
            for( int i = 0; i < listCategory.length(); i++ ) {
                JSONObject entry = listCategory.getJSONObject(i);
                //DO STUFF
            }
StErMi
  • 5,389
  • 5
  • 48
  • 71
  • What should I pass in fileContent? Yes,I know that it is string. But how to pass this string in my case? Please give me its format – Krishna Suthar May 07 '12 at 09:13
  • fileContent is the content of your file in res/raw. Do you also need the code to load that? – StErMi May 07 '12 at 09:18
1

Android framework has a helper JsonReader in android.util package

Works like a charm, presented great example. In first block small error with absent square bracket '}':

public List readJsonStream(InputStream in) throws IOException {
     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
     try {
       return readMessagesArray(reader);
     } finally {
       reader.close();
     }
}

Also exists great library from google-devs GSON, which gives you possibility to map json structure straight to Java model: take a look here

Henadzi Rabkin
  • 6,834
  • 3
  • 32
  • 39
0
  1. Read it into a String
  2. Create a JSONArray with the retrieved String
  3. Use get() methods to retrieve its data
avimak
  • 1,628
  • 11
  • 18