Ali Baksh
Ali Baksh

Reputation: 41

JSON data parsing in android

I am having trouble in parsing JSON. I have a string as such,

String result = "[{"id":"1","brand_name":"Unilever","brand_image":"collaboration_2.jpg","brand_description":"Unilever is the world's leading company and blah blah ","is_active":"1"},{"id":"2","brand_name":"Engro","brand_image":"people-icon-in-vector-format14.jpg","brand_description":"Engro is another brand and blah blah blah blah\r\n","is_active":"1"}]";

and here is trying code i am trying but getting null pointer exception

String brands[] = null;

JSONArray data = new JSONArray(result);

for(int j=0; j<data.length();j++){
    brands[j] = data.getJSONObject(j).getString("brand_name");
}

Upvotes: 0

Views: 400

Answers (3)

Parth Doshi
Parth Doshi

Reputation: 4208

I once tried parsing a JSON String returned by my web service. Here is what I did:

The response I got from the web service was:

{"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}

In order to parse I did the following:

  JSONObject jsonobject = new JSONObject(result);
  JSONArray array = jsonobject.getJSONArray("checkrecord"); 
  int max = array.length();

 for (int j = 0; j < max; j++) 
 {
  JSONObject obj = array.getJSONObject(j);
  JSONArray names = obj.names();


 for (int k = 0; k < names.length(); k++) 
 {
  String name = names.getString(k);
  String value= obj.getString(name);  

 }

}

My JSONObject looks like this:

{"Table1":[],"checkrecord":[{"missed":34,"attended":12,"percentage":40,"rollno":"abc2"}]}

You need to do modifications as per your code and requirements.

Hope it helps

Cheers

Upvotes: 0

EsbenG
EsbenG

Reputation: 28162

I'd recommend to look into GSON. It really makes working with json easy. Heres link: http://code.google.com/p/google-gson/

Upvotes: 1

Joy George Kunjikkuru
Joy George Kunjikkuru

Reputation: 1527

I am not a Java guy .It seems to me that you should initialize the brands[] variable before using it.

Also check for variable data for null & data.getJSONObject(j) before calling the method.

Upvotes: 3

Related Questions