NSAarry to NSDictionary - ios

I have an NSArray that looks like this
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"main: %#", [dataDict valueForKey:#"main"]);
main: [{"city": "dallas", "description": "this is my test description"}]
And I am trying to turn it into a NSDictionary so I get get element like [mainDict objectForKey#"city"]
So I tried this
NSLog(#"%#", [[mainArray objectAtIndex:0] objectForKey:#"city"]);
Thinking it would get the first element in mainArray and then the object that I want but I keep getting this error
[__NSCFString objectAtIndex:]: unrecognized selector sent to instance
How can I make the NSAarry into a NSDictionary?
Thanks

Create a for loop for list when you get response in [{},{}] format that means its a list of elements . Or you can ask your API developer to correct the error .
Any ways simple solution here is :
for (NSDictionary *d in [dataDict valueForKey:#"main"]){
NSlog (#"%#",d);
NSlog (#"%#",[d objectForKey :#"city"]);
}

Your error is saying mainarray is not a NSArray, it is NSString. So please check like this
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"main: %#", [dataDict valueForKey:#"main"]);
if ([[dataDict valueForKey:#"main"] isKindOfClass:[NSArray class]]) {
NSArray *mainArray = [dataDict valueForKey:#"main"];
NSLog(#"City == %#",[[mainArray objectAtIndex:0] objectForKey:#"city"]);
}else{
NSLog(#"mainarray is kind of -> %#", NSClassFromString([dataDict valueForKey:#"main"]));
}

NSArray *mainArray = #[#{#"city":#"dallas", #"description":#"this is my test description"}];
NSLog(#"%#", [[mainArray objectAtIndex:0] objectForKey:#"city"]);
no problem ....

Related

Single object json parse - what am I doing wrong?

This has got to be something obvious that I am doing wrong. I have been banging my head against a wall trying to figure out what is going on. I already have this json parsing done in the android version of my app, now trying to parse this simple json in xcode and can't get it done.
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
NSLog([res objectForKey:#"Date"]);
This code get me the "unrecognized selector sent to instance" error.
Here is the json data and you can see Date is one of the objects:
[{"Date":"2016-06-17T22:56:33.0811255-05:00"}]
Thanks in advance for any help on this issue. I've tried to simplify this post, but if more info is needed I will try and quickly provide.
http://i.stack.imgur.com/Y5fsT.png
JSONObjectWithData is returning an array of dictionaries and not a dictionary. Your print out of the raw JSON confirms this:
[{"Date":"2016-06-17T22:56:33.0811255-05:00"}] // This is an array
However you're attempting to treat that response object like a dictionary. In doing so you're calling a dictionary method (objectForKey:) on an array. This results in a crash. Try something like this:
NSError *error = nil;
id responseObject = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];
if (error)
{
// Handle error
return;
}
NSLog(#"%#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]])
{
NSArray *responseArray = (NSArray *)responseObject;
for (id item in responseArray)
{
NSLog(#"%#", item);
if ([item isKindOfClass:[NSDictionary class]])
{
NSDictionary *dictionary = (NSDictionary *)item;
NSString *dateString = [dictionary objectForKey:#"Date"];
NSLog(#"%#", dateString);
}
}
}
else
{
// responseObject is not an array...
}
I'm pretty sure this is because you should first set res as [NSDictionary]. Then pick the first element in that array and then get objectForKey: "Date". Normal JSON Data starts with a {, this starts with a [. Which means it's an array.
You can see it for yourself in the screenshot when it says #: 1 Element . THEN it says 1 key/value pair. The NSDictionary is inside an array.NSError
Try this code:
*myError = nil;
[NSDictionary] *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
if (res.count > 0) {
NSLog([res[0] objectForKey:#"Date"]);
}

Mapping JSON response field into NSArray

Response:
{"rsBody":
[{"productId":11,
"productImageUrl":"http:xxxx"},
{"productId":9,
"productImageUrl":"http:"xxxx"}]}
I know this is a repeated question, but still asking cause not getting the right way to do it. I am getting some response from php server as JSON in an array which consists two objects. I want to map the element of both objects productImageUrl in an NSArray. Resultant array should be somewhat like
NSArray =[{#"url":"productImageUrl1"},{#"url":#"ProductImageUrl2"}, nil];
productImageUrl1 = element of 1st object, productImageUrl2 = element of 2nd object.
I am parsing the response and able to to extract it from rsBody.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization
JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
Try this:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary* response = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
for (NSDictionary *dict in rsBody)
{
NSMutableDictionary *dictURL = [[NSMutableDictionary alloc] init];
[dictURL setValue:[dict valueForKey:#"productImageUrl"] forKey:#"url"];
[arr addObject:dictURL];
}
NSLog(#"%#", arr);

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x11c824e0

I face this error, Please help me for this and here is my code:
if(![[tmparr objectForKey:#"error"] isEqualToString:#"No data found"]){
resultArray = [NSArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]];}
The problem is that tmparr is a variable of type NSArray, but i guess you're treating it as an NSDictionary in this line:
[tmparr objectForKey:#"error"];
I solve this issue thanks to all
if( [tmparr isKindOfClass:[NSDictionary class]] && ![[tmparr objectForKey:#"error"] isEqualToString:#"No data found"]){
resultArray = [NSArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]];
}

JSON not working as expected on iOS

I'm currently trying to parse this JSON
[{"id":"1","dish_name":"Pasta & ketchup","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKetchup\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"},{"id":"2","dish_name":"Pasta & Kødsovs","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKødsovs\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"}]
But it fails and crashes with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSError *error = NULL;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
recipes = [[NSArray alloc] initWithArray:[json objectForKey:#"dish_name"]];
[uit reloadData];
}
Do someone have any clue, why it crashes with error -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8077240
?
Thanks in advance.
The error message beginning with [__NSCFArray objectForKey:] means that you have an NSArray (the root object of the JSON is an array - notice the opening and closing square brackets) and you're trying to treat it as a dictionary. All in all,
recipes = [[NSArray alloc] initWithObject:[json objectForKey:#"dish_name"]];
should be
recipes = [[NSArray alloc] initWithObject:[[json objectAtIndex:0] objectForKey:#"dish_name"]];
Note that there are two objects in the array, so you might want to use [json objectAtIndex:1] as well.
Edit: if you have a dynamic number of recipes, you can do this:
recipes = [[NSMutableArray alloc] init];
for (NSDictionary *dict in json) {
[recipes addObject:[dict objectForKey:#"dish_name"]];
}
If your json NSDictionary were a real & valid NSDictionary object, your call to this:
[json objectForKey:#"dish_name"]
should return exactly this:
"Pasta & ketchup"
Which is definitely not an array. It's a NSString object.
Which would be why the call to "initWithArray" is bombing.

JSON parse returns null

i need to parse the Apple JSON but i have a little problem. I'm now doing this:
The problem is here:
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSNumber *resultCount = [json objectForKey:#"resultCount"];
NSLog(#"%i", [resultCount intValue]);
NSArray * AppStoreUrlParse = [json objectForKey:#"results"];
NSDictionary* StoreParse = [AppStoreUrlParse objectAtIndex:0];
NSLog(#"%#", [json objectForKey:#"price"]);
}
On this line:
NSLog(#"%i", [resultCount intValue]);
The NSlog is returing: 1 like in the JSON ( http://itunes.apple.com/lookup?id=387633954)
But on this line
NSLog(#"%#", [json objectForKey:#"price"]);
The NSLOG returns (Null)
does anyone know how i can get the price from the json?
It seems that 'price' is part of a dictionary that is the first item in the 'results' array.
Can you try
NSLog(#"%#", [[AppStoreUrlParse objectAtIndex:0] objectForKey:#"price"]);
This would get the value of the key 'price' in the first element of the 'results' array of your JSON.
EDIT
Actually, rereading your code, you are already getting the first element of the array in this line:
NSDictionary* StoreParse = [AppStoreUrlParse objectAtIndex:0];
So all you need to do is change json by StoreParse in your NSLog:
NSLog(#"%#", [StoreParse objectForKey:#"price"]);

Resources