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.
Related
I am a newbie in iOS development. I was trying to put the results of an NSMutableArray into an NSMutableString but this is resulting in an NSException.
Here is my code:
NSMutableArray *oldtableData = .......this is where I recieve card data;
NSError *error;
NSMutableData *tableDataUpdated = [[NSJSONSerialization dataWithJSONObject:oldtableData
options:0
error:&error] copy];
NSMutableDictionary *cardDictionary = [NSJSONSerialization JSONObjectWithData:tableDataUpdated options:0 error:NULL];
For converting the cardDictionary into a NSMutableArray, I am using this piece of code (which is giving me an NSException)
NSMutableArray *type = [NSMutableArray array];
NSMutableArray *last4Digits = [NSMutableArray array];
[cardDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[type addObject:[obj valueForKeyPath:#"type"]];
[last4Digits addObject:[obj valueForKeyPath:#"last4Digits"]];
}];
But If I exclude the above code and try NSLog with this piece of code
NSLog(#"JSON: %#",cardDictionary);
Console will give a proper json result; something like this:
JSON: (
{
cardPciId = "###########";
fingerPrint = ###########;
last4Digits = 4321;
type = Mastercard;
},
{
cardPciId = "###########";
fingerPrint = ###########;
last4Digits = 1234;
type = Visa;
}
)
I am trying to convert this into two Arrays, one with all the "type"s and another one with all "last4Digits". But this is what I get
Uncaught exception: -[__NSCFArray enumerateKeysAndObjectsUsingBlock:]:
unrecognized selector sent to instance 0x7ff7060badf0
I tried to hover through StackOverFlow to find a solution but none of them seem to be working. :(
It looks like cardDictionary is actually an NSArray instance containing the dictionaries. So, you should iterate through the array, and get type and last4Digits from each dictionary using objectForKey instead of valueForKeyPath:
NSArray *cardDictionaries = [NSJSONSerialization JSONObjectWithData:tableDataUpdated options:0 error:NULL];
NSMutableArray *type = [NSMutableArray array];
NSMutableArray *last4Digits = [NSMutableArray array];
[cardDictionaries enumerateObjectsUsingBlock:^(NSDictionary *cardDictionary, NSUInteger idx, BOOL *stop) {
[type addObject:[cardDictionary objectForKey:#"type"]];
[last4Digits addObject:[cardDictionary objectForKey:#"last4Digits"]];
}];
There is a lot going on here, but I want to point one thing out.
Table data is being serialized to JSON.
NSMutableData *tableDataUpdated = [[NSJSONSerialization dataWithJSONObject:oldtableData
options:0
error:&error] copy];
Next, the data that was just serialized is de-serialized. It will always be the same array.
NSMutableDictionary *cardDictionary = [NSJSONSerialization JSONObjectWithData:tableDataUpdated options:0 error:NULL];
You will always get the same data back. You don't need to do the JSON step at all.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[jsonArray removeAllObjects];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
for (int i=0; i<[sdf count]; i++) {
myDict=[sdf objectAtIndex:i];
[myArray addObject:[myDict objectForKey:#"RxnCustomerProfile"]];
}
jsonArray=[myArray mutableCopy];
NSMutableDictionary *dict=[jsonArray objectAtIndex:0];
if ([dict count]>1) {
// Showing AlertView Here
}
}
}
Hi Everyone, I have an issue regarding the -[__NSArrayM objectForKey:]: .
Tried to solve but did not get the better solution for it. Please help me to
find the solution. Thanks In Advance
Below is the issues
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x19731d40'
This is a debugging problem and nobody can really solve it for you as you are using non-local variables whose definition and values are unknown, don't mention that you are using SBJSON (I guess), etc. But let's see if we can give you some pointers. Your error:
[__NSArrayM objectForKey:]: unrecognized selector sent to instance
That tells you that you sent a dictionary method (objectForKey) to an array (__NSArrayM). So somewhere you have an array when you think you have a dictionary.
Now you declare and allocate a dictionary:
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
but then assign to it:
myDict=[sdf objectAtIndex:i];
So this discards the dictionary you allocated and instead assigns whatever is at index i in the array sdf. How do you know, as opposed to think, that the element of the array is a dictionary? You don't test to check...
So where did sdf come from? This line:
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
So that calls JSONValue on some unknown string, assumes the result is a dictionary (could it be an array? or a failure?), looks up a key (did your error come from this line?), and assumes the result is an array.
So what you need to do is go and test all those assumptions, and somewhere you'll find an array where you think you have a dictionary.
Happy hunting!
YOU FETCH THE VALUE IN ARRAY FORMAT AND YOU INTEGRATE METHOD IN DICTIONARY.
You do not need to iterate keys and values of dict can directly pass values to array inside else part like:
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
Key RxnCustomerProfile itself containing array not dictionary.
Change your if else part use below code:
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
}
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
Check Sdf
if([sdf isKindOfClass:[NSDictionary class]])
{
NSLog(#"Dictionary");
}
else if([sdf isKindOfClass:[NSArray class]])
{
NSLog(#"NSArray");
}
else if([sdf isKindOfClass:[NSMutableArray class]])
{
NSLog(#"NSMutableArray");
}
First of all it seems like your json is not actually correctly formatted. Without knowing what responseData looks like it's difficult to say exactly what is wrong. But in your code there are a few areas where it can be improved.
First of all you don't need to use [responseString JSONValue]. You can short circuit it entirely with
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *sdf = responseDictionary[#"DataTable"];
Now, the rest all depends on the data in responseData.
But you can make your code a little bit cleaner with (if I understand what you're trying to achieve correctly:
NSMutableArray *myArray = [NSMutableArray array];
if ([sdf isEqual:[NSNull null]]) {
// Showing AlertView here
} else {
for (NSDictionary *myDict in sdf) {
[myArray addObject:dict[#"RxnCustomerProfile"]];
}
}
// No idea what you're trying to achieve here, but here goes:
jsonArray = [myArray mutableCopy];
NSDictionary *dict = jsonArray.first;
if (dict.count > 1) {
// Showing AlertView here
}
Some things to note. You make very liberal use of NSMutableArray and NSMutableDictionary for no apparent reason. Only use mutable if you're actually changing the array or dictionary.
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);
I just used this answer to set up a data request from Yahoo Finance. If you take a look at the post, you'll see it returns a dictionary of data (in this case, bids) and keys (symbols). Just to test it, I used this code, but it continues to crash:
NSArray *tickerArray = [[NSArray alloc] initWithObjects:#"AAPL", nil];
NSDictionary *quotes = [self fetchQuotesFor:tickerArray];
NSLog(#"%#",[quotes valueForKey:#"AAPL"]);
Can you point out what I'm doing wrong? I need to get a string containing the data for the symbols I ask for.
PLEASE NOTE:My code is using the code that this post was based on, i.e. this.
The code you liked to is making the wrong assumption about the shape of the JSON data coming back from the API and you're getting a standard KVC error. reason: '[<__NSCFString 0x7685930> valueForUndefinedKey:]: this class is not key value coding-compliant for the key BidRealtime.'
With some debugging I got it working...
Based on your input array and by slightly modifying the function linked too, you need to access the quote like so:
#define QUOTE_QUERY_PREFIX #"http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20BidRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("
#define QUOTE_QUERY_SUFFIX #")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
+ (NSDictionary *)fetchQuotesFor:(NSArray *)tickers {
NSMutableDictionary *quotes;
if (tickers && [tickers count] > 0) {
NSMutableString *query = [[NSMutableString alloc] init];
[query appendString:QUOTE_QUERY_PREFIX];
for (int i = 0; i < [tickers count]; i++) {
NSString *ticker = [tickers objectAtIndex:i];
[query appendFormat:#"%%22%#%%22", ticker];
if (i != [tickers count] - 1) [query appendString:#"%2C"];
}
[query appendString:QUOTE_QUERY_SUFFIX];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] : nil;
NSDictionary *quoteEntry = [results valueForKeyPath:#"query.results.quote"];
return quoteEntry;
}
return quotes;
}
You'll notice the difference between the code I've posted here and the function you linked too is the final parsing of quoteEntry. I worked out what it was doing with some breakpoints, specifically on all exceptions that lead me to the exact line.
All you have to do is initialize the NSMutableDictionary!
NSMutableDictionary *quotes = [[NSMutableDictionary alloc] init];
BTW the guy above is totally NOT making use of the quotes dict. straight up returning the quoteEntry. Skipping one step. :)
I created a JSON using a PHP script.
I am reading the JSON and can see that the data has been correctly read.
However, when it comes to access the objects I get unrecognized selector sent to instance...
Cannot seem to find why that is after too many hours. Any help would be great!
My code looks like that:
NSDictionary *json = [[NSDictionary alloc] init];
json = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
NSLog(#"raw json = %#,%#",json,error);
NSMutableArray *name = [[NSMutableArray alloc] init];
[name addObjectsFromArray: [json objectForKey:#"name"]];
The code crashes when reaching the last line above.
The output like this:
raw json = (
{
category = vacancies;
link = "http://blablabla.com";
name = "name 111111";
tagline = "tagline 111111";
},
{
category = vacancies;
link = "http://blobloblo.com";
name = "name 222222222";
tagline = "tagline 222222222";
}
),(null)
2012-06-23 21:46:57.539 Wind expert[4302:15203] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0xdcfb970
HELP !!!
json is an array from what you've shown, not a dictionary. I can tell this because of the parentheses surrounding the whole of the log output for json. Inside the array are dictionaries, which I can tell by the fact that they are surrounded by braces.
So, it looks like you want something like this:
NSError *error = nil;
NSArray *json = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
NSLog(#"raw json = %#,%#",json,error);
NSMutableArray *name = [[NSMutableArray alloc] init];
for (NSDictionary *obj in json) {
[name addObject:[obj objectForKey:#"name"]];
}
As an aside you will notice I have removed the unnecessary initialisation of json to an object before overwriting in the next line with JSONObjectWithData:options:error:. In an ARC world it wouldn't be a leak but it's still completely unnecessary to allocate an object just to get rid of it again a moment later. Also I added in the NSError *error = nil; line since that was not there and was obviously necessary to compile.
The problem appears to be that the root level of your JSON is an array, not a dictionary (note the parenthesis instead of curly brace as the first character in the logged output). Arrays do not have objectForKey selector. Perhaps you intend to take objectAtIndex:0 first, or else iterate over all the the items?
As an aside, the first line of your code makes a completely wasted initialization of an NSDictionary. It is simply overwritten and deallocated on the very next line.