ASP_Soldier ASP_Soldier - 2 years ago 97
iOS Question

iOS JSON/NSArray as string

Given the following data structure, how do I access the value from key

) as a string, from the following

enter image description here


I tried

NSArray *Temp=responseObject;
NSData *serialized = [NSKeyedArchiver archivedDataWithRootObject:Temp];
[[NSUserDefaults standardUserDefaults] setObject:serialized forKey:@"Temp"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSData *volume = [[jsonArray objectAtIndex: 0] objectForKey:@"field2"];

But I get a SIGABRT Error...

Answer Source

It appears that your data is actually an instance of NSDictionary, not NSArray. One way to recognize is this is to notice that the top level keys [0], [1] each display a key (such as @"channels") and a value (9 key/value pairs.)

But, you don't seem to be showing all of your code, because jsonArray is not declared in the snippet you posted. So, assuming the object you posted is jsonArray, you probably want this:

NSArray *feeds = jsonArray[@"feeds"];
NSDictionary *firstFeed = feeds[0];
NSString *field2 = firstFeed[@"field2"];

You can combine those calls into this, if you wish:

NSString *field2 = jsonArray[@"feeds"][0][@"field2];

A couple of other notes:

  • You don't need to call [NSUserDefaults synchronize] as of several iOS releases ago. This is not your crash, but worth pointing out.
  • If you're trying to save JSON from an API into NSUserDefaults, or really work with JSON at all in Objective-C, you can use NSJSONSerialization instead of NSKeyedArchiver.
  • It's common style to use lowercase the first letter of most variable names (like you did with serialized and volume) instead of uppercase (like you did with Temp.)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download