-1

I'm playing with the JSON parser in iOS.

But I was wonder how one would actually parse something (a bit) more complicated, my JSON shows data like this :

"terms":"3",
"results":
 {
   "Events":[
   {
     "Event_Name":"3 Doors Down",
     "Event_NavigateURL":"3-doors-down"
   },
   {
     "Event_Name":"Alabama 3",
     "Event_NavigateURL":"alabama-3"
   },
   {
     "Event_Name":"Belsonic 2013",
     "Event_NavigateURL":"belsonic-2013"
   },
   {
     "Event_Name":"Download Festival 2013",
     "Event_NavigateURL":"download-festival-2013"
   }
],
"Sports":{
},
"Venues":{
}
}

I want to fetch value of Event_Name, and want to store it in Tableview, How should i fetch this ?

I tried this, but didn't success i am getting SIGABRT ... (NSInvalidArgumentException),

cell.textLabel.text = [[[[arr objectAtIndex:indexPath.row] objectAtIndex:@"results"] objectForKey:@"Events"] objectForKey:@"Event_Name"];

Thanks In Advance...

Krunal
  • 6,440
  • 21
  • 91
  • 155

8 Answers8

3

First of all your json is invalid. If you put '{' in start and '}' at the end then it would be valid. Secondly, you should use online json parsing websites to see whether your json strings are valid or not. Try http://jsonviewer.stack.hu/

And for json parsing use NSJSONSerialization of NSJSON Kit. Go to this post for how to use it. How to use NSJSONSerialization

The objects in {} brackets means it's an NSDictionary Object and objects inside [] means they are part of NSArray object.

Community
  • 1
  • 1
Salman Zaidi
  • 9,342
  • 12
  • 44
  • 61
  • Always look for array objects and dictionary objects inside your json strings. If you access them differently your app will crash for sure.. – Salman Zaidi Apr 29 '13 at 09:49
  • How is that JSON invalid? – Anupdas Apr 29 '13 at 11:17
  • jsons strings start with [ ] brackets or { } brackets meaning either it's an NSArray type json or NSDictionary type object respectively. In your case your string has key value pairs meaning it's a NSDictionary object. So, for that the valid json must contain { in the start and } at the end of string showing opening and ending of dictionary object – Salman Zaidi Apr 29 '13 at 11:30
  • You are correct. There is no point in this discussion as the JSON is edited. Sorry for the trouble. – Anupdas Apr 29 '13 at 11:54
2

To display Event Names in TableView your array should store objects of Events, fetch Events from JSON in array as-

arr = [[JSONObject objectForKey:@“results”] objectForKey:@“Events”];

// and set cell text label as -

cell.textLabel.text =[[arr objectAtIndex:indexPath.row] objectForKey:@"Event_Name"];
Amzy
  • 56
  • 2
1

try like this may be it'l helps you,

  NSArray *array=[[[jsonarray objectAtIndex:0] valueForKey:@"results"] valueForKey:@"Events"];
    NSString *name=[[array objectAtIndex:indexPath.row] valueForKey:@"Event_Name"];
Balu
  • 8,470
  • 2
  • 24
  • 41
1

try turning

cell.textLabel.text = [[[[arr objectAtIndex:indexPath.row] objectAtIndex:@"results"] objectForKey:@"Events"] objectForKey:@"Event_Name"];

into

cell.textLabel.text = [[[[yourJsonDict objectForKey:@"results"] objectForKey:@"Events"] objectAtIndex:indexpath.row] objectForKey:@"Event_Name"];
gasparuff
  • 2,295
  • 29
  • 48
  • `[arr objectForKey:@"results"]` shows error – Krunal Apr 29 '13 at 09:47
  • oh yeah, it's an array... replace `arr` with the name of your Json Dictionary – gasparuff Apr 29 '13 at 09:49
  • Thanx for answering but same error.. – Krunal Apr 29 '13 at 09:53
  • Compile error? Try doing it step by step. E.g. go ahead and make a NSLog like this `NSLog(@"%@", [yourJsonDict objectForKey:@"results"])` then see what you get. Then do a `NSLog(@"%@", [[yourJsonDict objectForKey:@"results"] objectAtIndex:0]);` and so on. – gasparuff Apr 29 '13 at 09:57
1

Best Practice is to to See the structure Of the JSON in the Link : http://json.bloople.net/.

Paste your JSON response and you will find the proper structure.

Your JSON Structure is like : Array of Dictionary. So Use the Below Code to store the data in the array.

  id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

  arr = [[jsonObject objectForKey:@“results”] objectForKey:@“Events”];

Use the Below Code to Show the data in the Tableview.

cell.textLabel.text =[[arr objectAtIndex:indexPath.row] objectForKey:@"Event_Name"];
Siba Prasad Hota
  • 4,779
  • 1
  • 20
  • 40
0

The above is not a valid JSON(if above is the total response). Use jsonLint.com to validate.

You can try this:

 arr = [NSMutableArray arrayWithCapacity:[[dic objectForKey:@"Events"] count]];

for (NSDictionary *details in [dic objectForKey:@"Events"]){
[arr addObject:[details objectForKey:@"Event_Name"]];

}

then give arr as an input to UITableview

Ramu Pasupuleti
  • 888
  • 2
  • 15
  • 35
0

You can store the root object and get the data as you want. Access the data layer by layer. If you want to show events you can make an array for the events so that you can avoid doing the steps again and again.

@property (nonatomic, strong) NSDictionary *json;
@property (nonatomic, strong) NSArray *events;

NSError *error = nil;
self.json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:NSJSONReadingAllowFragments
                                                       error:&error];
NSDictionary *results = self.json[@"results"];
self.events = results[@"Events"];

//Access each event in events array and get the event name
NSDictionary *event = self.events[0];
NSString *eventName = event[@"Event_Name"];
Anupdas
  • 10,211
  • 2
  • 35
  • 60
-1

include the json frame work first .. http://longweekendmobile.com/2010/10/15/how-to-consume-json-or-xml-web-apis-on-iphone-smoothly/ and then follow :

NSError *error;
        SBJSON *json = [SBJSON new];
        NSDictionary *dict_item = [json objectWithString:resp_str error:&error];

        if (dict_item == nil)
            NSLog(@"%@", [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]]);
        else
            NSLog(@"items selected is : %@", dict_item);

You need to check weather it returns an array or a dictionary .. (actual return type is id)..

and then in this way you can ultimately get the value of event name

YogiAR
  • 2,207
  • 23
  • 44
  • 2
    Don't bother using SBJSON it is slower than native apis. – Fogmeister Apr 29 '13 at 09:43
  • i am able to parse my json data, here is my output of my log: `{ "terms":"3", "results":{ "Events":[ { "Event_Name":"3 Doors Down", "Event_NavigateURL":"3-doors-down" }, { "Event_Name":"Alabama 3", "Event_NavigateURL":"alabama-3" }, { "Event_Name":"Belsonic 2013", "Event_NavigateURL":"belsonic-2013" }, { "Event_Name":"Download Festival 2013", "Event_NavigateURL":"download-festival-2013" } ], "Sports":{ }, "Venues":[] } }` – Krunal Apr 29 '13 at 09:44
  • yes we do have own in built in classes for json parsing in ios these days .. but i was suggesting the simplest way .. – YogiAR Apr 29 '13 at 09:44