How to Serialize a NSCFArray (possible JSON) to NSDictionary? - ios

I'm really stuck right now while using BZForursquare to get nearby Venues into a UITableView.
BZFoursquare: https://github.com/baztokyo/foursquare-ios-api
I get my Requestresult inside the requestDidFinishLoading Delegate Method. In this Method the request Object contains several NSDictionaries and one Dictionary is in request.response. This response Dictionary contains one entry with key="venues" and as Value a JSON Object. When I put this value Object into a dictionary the type seems not to be a Dictionary but a NSCFArray:
#pragma mark BZFoursquareRequestDelegate
- (void)requestDidFinishLoading:(BZFoursquareRequest *)request {
self.meta = request.meta;
self.notifications = request.notifications;
self.response = [request.response objectForKey:#"venues"];
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"%#",[self.response objectForKey:#"name"]);
}
I assume this because the NSLog Line gives me the following error:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1e5c90f0
Now I'm totaly confused and tried some failed attempts to get this JSON from whatever kind od Datatype it is into a NSDictionary. One attempt was to put the value Object into an NSString and use
[NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
to get it into a Dictionary but that also failed because it still remains a NSCFArray. Can someone please tell me how I get content of
[request.response objectForKey:#"venues"]
into a NSDictionary so that I can populate my UITabelview with this content?
EDIT:
Here is whats in the value part from the Dictionary request.response:
(
{
categories = (
{
icon = {
name = ".png";
prefix = "https://foursquare.com/img/categories/food/default_";
sizes = (
32,
44,
64,
88,
256
);
};
id = 4bf58dd8d48988d10b941735;
name = "Falafel Restaurant";
pluralName = "Falafel Restaurants";
primary = 1;
shortName = Falafel;
}
);
contact = {
};
hereNow = {
count = 0;
groups = (
);
};
id = 4df3489dfa76abc3d86c4585;
likes = {
count = 0;
groups = (
);
};
location = {
cc = DE;
city = "Vinn";
country = Germany;
distance = 92;
lat = "51.44985";
lng = "16.648693";
state = "Nordrhein-Westfalen";
};
name = "Yildiz D\U00f6ner";
specials = (
);
stats = {
checkinsCount = 3;
tipCount = 0;
usersCount = 2;
};
verified = 0;
}
And this seems to be from Type of NSCFArray. And how can I create from this another Dictionary so that I can access the JSON Values by key? Sorry if I'm really slow today...

You ask for "venues" which I assume is an array of such. So after deserializing the json, log the return object to see what you get. It's almost for sure an array of dictionaries.

Related

Parsing Json Output correctly

I am trying to correctly target the elements within the Json Output and I am getting closer but I presume there is a easy and obvious way I am missing.
My Json looks like this with a upper level event.
JSON SNIPPET UPDATED
chat = (
(
{
Key = senderId;
Value = {
Type = 0;
Value = "eu-west-1:91afbc3f-890a-4160-8903-688bf0e9efe8";
};
},
{
Key = chatId;
Value = {
Type = 0;
Value = "eu-west-1:be6457ce-bac1-412d-9307-e375e52e22ff";
};
},
{
Key = timestamp;
Value = {
Type = 1;
Value = 1430431197;
};
},
//Continued
I am targeting this level using
NSArray *chat = array[#"chat"];
for ( NSDictionary *theCourse in chat )
{
NSLog(#"---- %#", theCourse);
// I tried the following to target the values
//NSLog(#"chatId: %#", [theCourse valueForKey:#"Key"]);
//NSLog(#"timestamp: %#", theCourse[#"senderId"] );
}
}
I need to parse the value data for each key which if I was using an array would do like [theCourse valueForKey:#"Key"] but I think I may not be going deep enough?
As you would expect, [theCourse valueForKey:#"Key"] gives me the Key values but I need the associate values of those keys.
You can create an easier dictionary:
NSArray *chat = array[#"chat"][0];
NSMutableDictionary* newDict = [NSMutableDictionary dictionary];
for (NSDictionary* d in chat)
[newDict setValue:d[#"Value"][#"Value"] forKey:d[#"Key"]];
Now you can use the newDict.
NSLog(#"chatId: %#", [newDict valueForKey:#"chatId"]);

How to efficiently extract data from JSON dictionary

I have recently used the following code to extract the ID of a location from a Foursquare API call with:
NSDictionary* foursquareJson = [NSJSONSerialization JSONObjectWithData:secureData options:kNilOptions error:&error];
NSDictionary *venuesDict = foursquareJson[#"response"];
NSArray *venuesArray = venuesDict[#"venues"];
NSDictionary *venuesDict2 = venuesArray[0];
NSArray *categoriesDict = venuesDict2[#"categories"];
NSDictionary *idDict = categoriesDict[0];
NSLog(#"ID is %#",idDict[#"id"]);
with original foursquareJson being:
2015-03-30 17:16:40.700 Voyagic[2833:718563] {
meta = {
code = 200;
};
response = {
venues = (
{
categories = (
{
icon = {
prefix = "https://ss3.4sqi.net/img/categories_v2/building/conventioncenter_";
suffix = ".png";
};
id = 4bf58dd8d48988d1ff931735;
name = "Convention Center";
pluralName = "Convention Centers";
primary = 1;
shortName = "Convention Center";
}
);
contact = {
formattedPhone = "+44 20 7222 5000";
phone = "+442072225000";
};
hereNow = {
count = 0;
groups = (
);
summary = "Nobody here";
};
id = 4b6599d4f964a520f8f52ae3;
location = {
address = "Broad Sanctuary";
cc = GB;
city = London;
country = "United Kingdom";
distance = 2167;
formattedAddress = (
"Broad Sanctuary",
London,
"Greater London",
"SW1P 3EE",
"United Kingdom"
);
lat = "51.49997800145596";
lng = "-0.1289014132864838";
postalCode = "SW1P 3EE";
state = "Greater London";
};
name = "Queen Elizabeth II Conference Centre";
referralId = "v-1427732200";
specials = {
count = 0;
items = (
);
};
stats = {
checkinsCount = 3657;
tipCount = 15;
usersCount = 2407;
};
verified = 0;
}
);
};
}
but there surely must be a better way of accessing the ID which I don't know about (instead of creating 4 dictionaries and 2 array, which seems somewhat excessive :/ ). Any help would be greatly appreciated :)
Ultimately, the data will need to be accessed through the lists of dictionaries and arrays somehow, it just depends on where you want that to happen. You could use or make a parser for the JSON but that will ultimately still need to map the JSON data similarly to what you are doing. A simple and shorter way of accessing the data would be to not create a new variable in every iteration. Although it really is not much different:
NSDictionary *foursquareJson = [NSJSONSerialization JSONObjectWithData:secureData options:kNilOptions error:&error];
NSDictionary *objectId = foursquareJson[#"response"][#"venues"][0][#"categories"][0][#"id"];
NSLog(#"ID is %#",objectId);
Because of the dialogue in the comments of this answer I figured I should probably include a bit more information about your concern with creating "4 dictionaries and 2 arrays". When you use the JSON Serializer to create native objects from the JSON (first line above) you are creating all of the arrays and dictionaries needed to fully represent and store the entire JSON. The difference in code samples between what you originally posted and what I provided is really not a significantly different. If you are concerned with creating too many dictionaries or arrays you should attempt to filter out the JSON prior to deserializing it into native objects.

NSDictionary - need to obtain value for key subelement

I have created an NSDictionary named "myData"
which contains the following JSON response:
{
listInfo = (
{
date = 1392157366000;
dateAsString = "02/11/2014 22:22:46";
id = 6;
address = 542160e0000c;
myLevel = 13;
},
{
date = 1392155568000;
dateAsString = "02/11/2014 21:52:48";
id = 5;
address = 542160e0000c;
myLevel = 13;
}
);
}
I need to retrieve each of the [dateAsString] key/value pairs.
I've tried: NSString *dateAsString=[[myData valueForKeyPath:#"dateAsString"][0] objectForKey:#"myData"]; without any luck.
Any suggestions are greatly appreciated.
I think this will work:
NSArray* dateStringArray = [listInfo valueForKeyPath:#"#unionOfObjects.dateAsString"]
I believe it will give you an array of strings. If you need to stuff that back in a dictionary, that should be fairly easy.
It's not clear what your "myData" looks like... so I used the listInfo array of dicts shown.

iOS - How to parse Json array in xcode and save results are strings

Hi I am trying to parse a Json string as an NSArray and save certain results as strings to set permissions for different users in my app. My current code is:
NSError *jsonParsingError1 = nil;
accountData = [NSJSONSerialization JSONObjectWithData:jsonAccount
options:NSJSONReadingMutableContainers error:&jsonParsingError1];
accountData is an NSMutableArray created in the .h file.
jsonAccount is NSData created by converted an NSString
The NSLog out put for the array is;
{
account = "XXXX";
companyName = XXXXX;
id = XXXXX;
websites = (
{
account = "XXXXX";
accountId = XXXXX;
anonymiseIP = 0;
companyName = XXXXX;
XXXX = 0;
domains = (
"XXXXX"
);
features = {
advancedSegmentation = 1;
attentionHeatmaps = 1;
domains = 0;
dotHeatmaps = 1;
goalConversionTracking = 1;
interactionHeatmaps = 1;
leadInfo = 0;
scrollHeatmaps = 1;
timeHeatmaps = 1;
users = 0;
valueHeatmaps = 1;
visitorPlayback = 1;
visitorScoring = 1;
visitors = 1;
};
fixedElementSelector = "";
flagClicksReceived = 0;
flagDataReceived = 0;
flagGoalsReceived = 0;
flagInteractionsReceived = 0;
flagScrollsReceived = 0;
id = XXXXX;
interactionSelector = "";
name = "XXXX";
permissions = (
segments,
heatmaps,
visitors,
campaigns,
support,
globalSettings,
websiteSettings
);
setCookies = 1;
status = 1;
statusMessage = "";
statusString = OK;
trialling = 1;
}
);
},
When I try and create a sting from one of the results and display it in the log I get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray:]: unrecognized selector sent to instance 0x6a950f0'
How can I save different keys as strings?
Looks like that your JSON is a Dictionary, not an Array.
Your JSON is not array you should parse it like NSDictionary
After parsing the JSON, you should test what kind of object it returned. E.g.:
if ([accountData isKindOfClass:[NSArray class]]) {
// handle like an array
} else if ([accountData isKindOfClass:[NSDictionary class]]) {
// handle like a dictionary
}
Your JSON is a dictionary with four keys: account, companyName, id, and websites.
The key "websites" will give you an array.
You can iterate through the "websites" array, and each element is a dictionary.
Each of the dictionaries in the "websites" array has lots of keys like account, accountId, anonymiseIP and so on. Some of these keys have values that are dictionaries or arrays.
In the NSLog statement, (a, b, c) would be an array, while { a = x; b = y; c = z; } would be a dictionary.
Your server response is a dictionary so change accountData to dictionary
Write NSLog for below and you will get information in it
[accountData objectForKey:#"account"];
[accountData objectForKey:#"companyName"];
[accountData objectForKey:#"id"];
[[accountData objectForKey:#"websites"] count];//array
[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"account"];
[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"];
[[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"]count]; //array
[[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"]objectAtIndex:0];

Parsing json returned by foursquare for iPhone gives Unrecognised leading character

I'm trying to get the nearby places using the foursquare api.
Here's the json data that is returned from
NSDictionary *results = [jsonString JSONValue];
NSLog(#"%#", results);
(
{
code = 200;
errorDetail = "This endpoint will stop returning groups in the future. Please use a current version, see http://bit.ly/lZx3NU.";
errorType = deprecated;
},
{
groups = (
{
items = (
{
categories = (
{
icon = "https://foursquare.com/img/categories/parks_outdoors/default.png";
id = 4bf58dd8d48988d163941735;
name = Park;
parents = (
"Great Outdoors"
);
pluralName = Parks;
primary = 1;
shortName = Park;
}
);
Then I try to get the list of the groups in an array with
NSArray *groups = [ (NSDictionary *)results objectForKey:#"groups"];
This returns the following error
2011-11-05 11:42:12.907 XperienzApp[1972:207] No of results returned: 0 Results : (null)
2011-11-05 11:42:13.225 XperienzApp[1972:207] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x5849cd0 {NSLocalizedDescription=Unrecognised leading character}"
)
2011-11-05 11:42:13.225 XperienzApp[1972:207] No of results returned: 0 Results : (null)
How should I parse this?
Edit:
I tried the suggested technique, this gives me an array
id groups = [[(NSDictionary *)results objectForKey:#"response"] objectForKey:#"groups"];
if ([results count] > 1){
NSLog(#"groups class %#\ngroups %# %d", groups, [groups class], [groups count]);
The log output is of the form:
{
categories = (
{
icon = "https://foursquare.com/img/categories/nightlife/danceparty.png";
id = 4bf58dd8d48988d11f941735;
name = Nightclub;
parents = (
"Nightlife Spots"
);
pluralName = Nightclubs;
primary = 1;
shortName = Nightclub;
}
);
contact = {
};
hereNow = {
count = 0;
};
id = 4eb33ba561af0dda8f673c1b;
location = {
address = "144 Willow St 4R";
city = Brooklyn;
crossStreet = Pierrepont;
distance = 462;
lat = "40.696864";
lng = "-73.996409";
postalCode = 11201;
state = NY;
};
name = "Entertainment 720, Ltd.";
stats = {
checkinsCount = 3;
tipCount = 0;
usersCount = 1;
};
verified = 0;
}
);
name = Nearby;
type = nearby;
}
)
groups __NSArrayM 1
This is again not json and is hard to parse, how do I get the output in json.
I'm the iPhone lead at foursquare. I'll try to take a stab at what's going on here.
First of all, I highly recommend you use JSONKit for your parser. It's lightweight and insanely fast: https://github.com/johnezang/JSONKit
It appears that you are parsing the JSON properly and getting the dictionary properly. Then you are logging the parsed object, not the original JSON. The output you are seeing is how Objective-C chooses to serialize the parsed dictionary to text. It is definitely not JSON. Using JSONKit, you could send the JSONString selector to your parsed result and convert it back to JSON and log that.
If you could provide some details on the problem you are trying to solve, I might be able to help you out more. And as Maudicus said, please pay attention to the error you are getting back. You don't want your app to break when we make the change to the API.
If the output below NSLog(#"%#", results); is your log statement. It appears your results variable is an array of dictionary objects.
Try to log the class of results to verify that NSLog(#"%#", [results class]);
If it is an array your groups object is the second object.
if ([results count] > 1)
id groups = [results objectAtIndex:1];
NSLog(#"groups class %#\ngroups %#", [groups class], groups);
Keep doing this until you understand the format of your data
Also the line
errorDetail = "This endpoint will stop returning groups in the future. Please use a current version, see http://bit.ly/lZx3NU.";
should be cause for concern. Check the documentation on foursquare for the current way of getting groups.

Resources