Parsing JSON objects error - objective-c

I have this JSON.
{
"cnt": 1,
"list": [
{
"object1": [
{
"subobject1": "value1",
"subobject2": "value2",
"subobject3": "value3"
}
],
"object2": {
"subobject1": value1,
"subobject1": value2,
"subobject1": value3
}
}
]
}
I can't get data from the first object. I receive an error
-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fa281f82520
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fa281f82520'
For the other object I get the data and I can see it in the NSLOG, but can't understand what's the problem with the first one and why the app is crashing.
This is how I parse the json in the DataModel
NSError *deserializationError;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &deserializationError];
NSArray * responseArr = json[#"list"];
NSMutableArray *result = [[NSMutableArray alloc] init];
if(responseArr && [responseArr isKindOfClass:[NSArray class]]) {
for(NSDictionary *cDictionary in responseArr) {
DAObject *cty = [[DAObject alloc] initWithDictionary:ctyDictionary];
if(cty) {
[result addObject:cty];
}
}
}
then In the Object .m file
DAServiceObject *object1 = [[DAServiceObject alloc] initWithDictionary:dictionary[#"object1"]];
self.value1 = object1.value1;
self.value2 = object1.value2;
and the app crashes.

You misinterpreted the data structure: "list" contains an array with only one item, i.e. a dictionary. This dictionary contains an array for each key (e.g. "item1"), again with only one item (again a dictionary).
edit
// ...
if(responseArr && [responseArr isKindOfClass:[NSArray class]]) {
NSDictionary *content = responseArr[0];
for (NSSString *key in [content allKeys]) {
NSDictionary *a = content[key][0];
// ...
}
}

Your JSON data is not an array. It is a dictionary. It's a dictionary with one key "cnt" and one key "list". The object under key "list" is an array.

Related

how to parse this JSON in OBJ c

I receive this JSON string from a web process
{
"result":"ok",
"description":"",
"err_data":"",
"data":[
{
"id":"14D19A9B-3D65-4FE2-9ACE-4C2D708DAAD8"
},
{
"id":"8BFD10B8-F5FD-4CEE-A307-FE4382A0A7FD"
}
]
}
and when I use the following to get the data:
NSError *jsonError = nil;
NSData *objectData = [ret dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json= [NSJSONSerialization JSONObjectWithData: objectData options:kNilOptions error: &jsonError];
NSLog(#"data: %#",[json objectForKey:#"data"]);
it gets logged as:
(
{
id = "14D19A9B-3D65-4FE2-9ACE-4C2D708DAAD8";
},
{
id = "8BFD10B8-F5FD-4CEE-A307-FE4382A0A7FD";
}
)
How can I parse the data as an NSDictionary with value and keys?
The web returns an object that has a property which is an array of objects, so...
NSDictionary *json= // your code
NSArray *array = json[#"data"];
for (NSDictionary *element in array) {
NSLog(#"%#", element);
// or, digging a little deeper
NSString *idString = element[#"id"];
NSLog(#"id=%#", idString);
}

Iterate through JSON array (App Crashing)

I am trying to iterate trough a JSON array to get both the item key and value.
This is my JSON array:
{
"ClientData": [{
"Name": "Michael"
}, {
"Last": "Ortiz"
}, {
"Phone": "5555555555"
}, {
"email": "test#gmail.com"
}],
"ClientAccess": [{
"T-Shirt": "YES"
}, {
"Meals": "NO"
}, {
"VIP": "YES"
}, {
"Registration Completed": "Pending"
}]
}
Now, I am trying to iterate through the "ClientData" array, but for some reason the app is crashing with this exception:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance
This is the code I am using to iterate through the JSON array:
NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
// Client Profile Data
NSDictionary *clientDataDict = [object objectForKey:#"ClientData"];
for (id item in clientDataDict)
{
[JSONUserData addObject:[clientDataDict objectForKey:item]];
}
This code was working fine when I didn't have each item on the JSON array placed inside an array. I did this to keep a consecutive order on the array.
Can someone give me any pointers on what the problem is?
Thank you!
ClientData is an array – represented by the square brackets [] – containing dictionaries with one key/value pair respectively (a quite cumbersome structure).
NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
// Client Profile Data
NSArray *clientDataArray = [object objectForKey:#"ClientData"];
for (NSDictionary *dict in clientDataArray) {
for (NSString *key in dict) {
[JSONUserData addObject:[dict objectForKey:key]];
}
}
According to your JSON strings, it looks like that ClientData pairs with an array and each item in array is a dictionary. Therefore, revised codes will look like:
NSMutableDictionary *mDict = [NSMutableDictionary new];
NSArray *array = [object objectForKey:#"ClientData"];
for (NSDictionary *item in array) {
[mDict addEntriesFromDictionary:item];
}

NSMutableDictionary using objectAtIndex

I am new to Xcode and I have created a NSMutableDictionary *dIc with following data:
Keys : ID , Name
Data :
ID = 1, Name = John
ID = 2, Name = Smith
I want to access dIc with specific row. I want this result for example :
Name = Smith.
I tried :
-(void)initiateArrays
{
dIc =[[NSMutableDictionary alloc] init];
}
- (void)viewDidLoad
{
[self initiateArrays];
[self callingWebSrvc];
[super viewDidLoad];
}
-(void)callingWebSrvc
{
NSInteger i=0;
do {
self.selectedRowId = [[mainMenuID objectAtIndex:i]integerValue];
[self getItemListFromWebSrvc];
i++;
} while (i<= mainMenuData.count - 1);
}
-(void) getItemListFromWebSrvc
{
//............ Request ....................................>>>
.
.
.
//............ Response ....................................>>>
NSInteger i = 0;
do {
elm = [xmlDataTable objectAtIndex:i];
//Set Object into Arrays
[dIc setObject:[NSNumber numberWithInt:selectedRowId] forKey:#"Id"];
[dIc setObject:[elm childNamed:#"Name"].value forKey:#"Name"];
NSArray *keys = [rowArray allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(#"%# is %#",key, [dIc objectForKey:key ]);
}
i=i+1;
} while (i <= xmlDataTable.count-1);
}
-(void)showResult
{
NSString *anObject = [[dIc objectForKey:#"Name" ] objectAtIndex:1];
NSLog(#"The Value is = %#",anObject );
}
but it's not working.
when i call [self showResult]; i got the following error:
-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x8b9a7f0
2014-02-26 00:53:57.718 iWish[3311:70b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x8b9a7f0'
The problem is this line:
NSString *anObject = [[dIc objectForKey:#"Name" ] objectAtIndex:1];
The first object in this story, [dIc objectForKey:#"Name" ], is an NSString. You are then saying objectAtIndex:1 to an NSString - and that is a no-no.

Unrecognized selector error when indexing into a dictionary of arrays

I have a dictionary of arrays that is causing __NSCFDictionary objectAtIndex: errors.
Can someone tell me why? The dictionary clearly has at least 1 array at the time of the error.
NSError *error;
responseString = [[NSString alloc] initWithData:self.responseData2 encoding:NSUTF8StringEncoding];
/* response string contains this:
{"words":
{
"word": {"rowsreturned":0,"id":"-1","date":"","word":"","term":"","definition":"","updated_on":""}
},
"status":"",
"rowsreturned":""
}
*/
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.responseData2 options:kNilOptions error:&error];
NSArray *todaysWord = [[json objectForKey:#"words"] objectForKey:#"word"];
//error here -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
NSDictionary *word = [todaysWord objectAtIndex:0];
In your case [[json objectForKey:#"words"] objectForKey:#"word"]; is returning a dictionary and not an array. Try doing the following,
id wordParam = [[json objectForKey:#"words"] objectForKey:#"word"];
if ([wordParam isKindOfClass:[NSArray class]]) {
NSDictionary *word = [(NSArray *)wordParam objectAtIndex:0];
} else if ([wordParam isKindOfClass:[NSDictionary class]]) {
NSDictionary *word = (NSDictionary *)wordParam;
} else {
NSLog(#"error. %# is not an array or dictionary", wordParam);
}
Your response string also shows that value for word is,
{"rowsreturned":0,"id":"-1","date":"","word":"","term":"","definition":"","updated_on":""}
which is a dictionary with key value pairs as rowsreturned:0, id:-1 etc..

Accessing JSON data inside an NSDictionary generated from NSJSONSerialization

Having some trouble accessing the JSON data in the following URL ( http://jamesstenson.com/portraits/?json=1 ), basically I want to access the "full" "url"'s underneath "attachments". My code at the moment is as follows:
NSError *e = nil;
NSData *jsonFeed = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://jamesstenson.com/portraits/?json=1"]];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:jsonFeed options:NSJSONReadingMutableContainers error: &e];
if (!jsonData) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in [jsonData objectForKey:#"page"]) {
for(NSDictionary *attachment in [item objectForKey:#"images"]) {
NSLog(#"%#", attachment);
}
}
}
This keeps throwing up an error:
2011-12-21 10:13:39.362 JSON[3463:f803] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a7b500
2011-12-21 10:13:39.363 JSON[3463:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a7b500'
I am aware I am accessing the items wrongly, but cannot figure out how to achieve this. I've tried several solutions such as http://blogs.captechconsulting.com/blog/nathan-jones/getting-started-json-ios5 - but no luck. I am complete newbie to iOS development and have a little knowledge of JSON. Thanks for everyones help in advance.
The problem is in you for loop
for(NSDictionary *item in [jsonData objectForKey:#"page"])
You won't get NSDictionary in item, it will return you key of Dictionary, which would be NSString
Check this link for each loop in objective c for accessing NSMutable dictionary to know how to traverse through NSDictionay
Below is the modified code for your requirement, might help you
if (!jsonData) {
NSLog(#"Error parsing JSON: %#", e); } else {
NSArray *attachments = [[jsonData objectForKey:#"page"] objectForKey:#"attachments"];
for(NSDictionary *object in attachments) {
NSLog(#"%#", [object objectForKey:#"images"]);
NSLog(#"%#", [[[object objectForKey:#"images"] objectForKey:#"full"] objectForKey:#"url"]);
}
}