How choose array in JSON - ios

I have some problem in my project. So i used JSON for take some information.
When i have JSON with folders(example: i have NSDictionary with name Playlist in this playlist i have NSString name and album) for this i make this code:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSDictionary *playlist =[allDataDictionary objectForKey:#"playlist"];
for (NSDictionary *diction in playlist) {
NSDictionary *artist = [diction objectForKey:#"artist"];
NSDictionary *song = [diction objectForKey:#"song"];
NSString *name = [artist objectForKey:#"name"];
NSString *namesong = [song objectForKey:#"name"];
[array addObject:name];
[array2 addObject:namesong];
}
[[self tableTrack]reloadData];
}
It's work perfect! BUT! When i don't have any folders, only, JSON without NSDictionary only NSStrings, how make? Sorry for my stupid question but really i tried write:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSString *name = [allDataDictionary objectForKey:#"name"];
NSString *namesong = [allDataDictionary objectForKey:#"name"];
[array addObject:name];
[array2 addObject:namesong];
}
[[self tableTrack]reloadData];
}
But i have error, also my app crashed:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x7615c90'
So, what i doing wrong?

The error says you have an NSArray, not an NSDictionary. This corresponds to a JSON array:
[
{ "name" : "fred" },
{ "name" : "jane" }
]
Here you have an array of dictionaries. You may want:
NSArray *people = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
for (NSDictionary *person in people) {
NSLog(#"name is %#", person[#"name"];
}

Related

iOS: -[NSTaggedPointerString objectForKey:]: crash

This is the following code I have
id dataDict = [NSPropertyListSerialization
propertyListWithData:[dictionaryStr dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
format:NULL
error:NULL];
if ([dataDict isKindOfClass:[NSDictionary class]]) {
for (NSString *key in dataDict) {
// value string crashes with the following exception -[NSTaggedPointerString objectForKey:]:
NSString *value = [dataDict objectForKey:key];
}
}
There is a user who is having a crash occur on the following line NSString *value = [dataDict objectForKey:key]; according to crashlytics. This doesn't make any sense to me because I check beforehand if dataDict belongs to the NSDictionary class. Can someone please explain to me how I can prevent this crash?

Failed to parse

I tried to parse this:
{"event":[{"event_id":"9","title":"event 10","welcome_logo":"20140715130727_252.png"}],"succeed":1}
This is my code:
NSString *strURL=[NSString stringWithFormat:#"http://loc**host/summit/event_login.php"];
NSData *dataURL=[NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult=[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSArray *jsonArray=[NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSDictionary *element=[jsonArray objectAtIndex:0];
NSString *title = [element objectForKey:#"title"];
NSString *image = [element objectForKey:#"welcome_logo"];
But this guy came and disturbs me:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x9e7d010'
So I'm wondering what I did I do wrong. I tried to google it and many said that I assume to use an array when the data is actually a dictionary. Is that true? So what do I need to do?
Change
NSArray *jsonArray=[NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSDictionary *element=[jsonArray objectAtIndex:0];
to
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSArray *events = [jsonDict objectForKey:#"event"];
if ([events count] > 0) {
NSDictionary *element=[events objectAtIndex:0];
}
because your json data is in the form of dictionary. And event holds the list (array) of events. And do a count check before accessing objectAtIndex: from events.

Parsing Json in iOS without keys common

My JSON String is :
[
{'Local':'webaddress'},
{'QA':'webaddress1'}
]
My Code is :
NSMutableDictionary *dataDictonary = [NSJSONSerialization
JSONObjectWithData:responseData
options:0
error:nil];
NSArray *keys = [dataDictonary allKeys];
NSArray *values = [dataDictonary allValues];
int i=0;
NSLog(#"",[keys count]);
NSLog(#"",[values count]);
int i=0;
for ( NSString *items in keys )
{
NSLog(#"----");
NSLog(#"Name: %#", items);
NSLog(#"Address: %#", values[i++]);
NSLog(#"----");
}
Here i get size as nothing blank in NSlog and can't Parse this value don't don't why. Please help..
Your JSON is an Array with Objects inside so you need to convert it to a NSArray:
NSString *json_string = #"[{\"Local\": \"webaddress\" }, {\"QA\": \"webaddress1\" }]";
NSError *error;
NSArray *JSON =
[NSJSONSerialization JSONObjectWithData: [json_string dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
NSLog(#"Local: %#", JSON[0][#"Local"]); // output is: Local: webaddress
UPDATE
// itherate through array
for(NSDictionary *dictionary in JSON)
{
//now you can iterate throug each dicitonary
NSEnumerator *enumerator = [dictionary keyEnumerator];
id key;
while((key = [enumerator nextObject])){
NSLog(#"key=%# value=%#", key, [dictionary objectForKey:key]);
}
}
Log looks like this:
key=Local value=webaddress
key=QA value=webaddress1

get value from NSDictionary not work

1.I get JSON data from web services and add It's to NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
2.Then I Show "dic" in NSLog It's present
{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]}
3.Then I get data value from "dic" in to new NSDictionary "dt"
NSDictionary *dt = [dic objectForKey: #"query"];
4.Then I Show "dt" in NSLog It's present
({ID = 01;IndexNo = 1;Picture = "img/food-48.png";})
5.I want to get "ID" from "dt". I use this code
NSString *ID = [dt objectForKey: #"ID"];
but it's error
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8a40a60
Can you try this
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSArray *arr = [dic objectForKey: #"query"];
NSDictionary *dt = arr[0];
NSString *ID = [dt objectForKey: #"ID"];
[dic objectForKey: #"query"] returns an NSArray actually. Note these square brackets in the output from the first NSLog statement:
{"query": [...]}
Try this:
NSArray *dtArray = [dic objectForKey: #"query"];
NSDictionary *dt = dtArray[0];
NSString *ID = [dt objectForKey:#"ID"];
Or to use the key-value coding behavior of NSDictionary and NSArray:
NSString *ID = [[dic valueForKeyPath:#"query.ID"] firstObject];
NSDictionary *dt = [[dic objectForKey: #"query"] objectAtIndex:0];
NSString *ID = [dt objectForKey: #"ID"];
You are trying to get value for key from array. change these lines.
From your jsonStructure
{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]}
object for key "query" is an array as {} is a dictionary and [] is an array. so do the following
NSArray *tempArray = [dt objectForKey:#"query"];
NSDictionary *tempDictionary = [tempArray objectAtIndex:0];
NSString *ID = [tempDictionary objectForKey:#"ID"];
Hope this helps.

Unrecognized selector sent to instance in JSON parsing

Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.

Resources