Parsing Json Output correctly - ios

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"]);

Related

Getting values from key in NSDictionary

I'm using the Edmunds API to return a JSON string of vehicle makes for a certain year.
The resulting NSDictionary looks like this:
makes = (
{
id = 200002038;
models = (
{ // not relevant
}
);
name = Acura;
niceName = acura;
},
{
id = 200001769;
models = (
{ // not relevant
}
);
name = "Aston Martin";
niceName = "aston-martin";
},
There are a lot more values in this dictionary...how can I loop through through the dictionary to retrieve each of the 'name' values?
I like valueForKeyPath because you can do so much with it and it's a one line solution. Tested this and it works in my dev setup. If you know your data is in a predictable format, then you can do amazing things with valueForKeyPath.
NSArray *makeNames = [makes valueForKeyPath:#"name"];
Great info on valueForKeyPath http://nshipster.com/kvc-collection-operators/
NSMutableArray *makeNames = [NSMutableArray new];
for (NSDictionary *make in makes) {
NSLog(#"Make name: %#", make[#"name"]);
[makeNames addObject:make];
}
NSLog(#"Makes array: %#", makeNames);

JSON Parsing Issue

Hello I am new to iOS development. I am trying to parse a JSON response. Below is the top part of the response:
Table =
{
Rows = {
results = (
{
Cells = {
results = (
{
Key = Rank;
Value = "6.251145362854";
ValueType = "Edm.Double";
"__metadata" = {
type = "SP.KeyValue";
};
},
{
Key = DocId;
Value = 978473;
ValueType = "Edm.Int64";
"__metadata" =
{
type = "SP.KeyValue";
};
},
{
Key = WorkId;
Value = 978473;
ValueType = "Edm.Int64";
"__metadata" = {
type = "SP.KeyValue";
};
},
{
Key = Title;
Value = "Vneea Ready!";
ValueType = "Edm.String";
"__metadata" =
{
type = "SP.KeyValue";
};
},.........................
Now I am using
NSError *error;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSDictionary *results = jsonObject[#"Table"][#"Rows"][#"results"];
So I was able to refine it until here, but then I use
NSDictionary *results = jsonObject[#"Table"][#"Rows"][#"results"][#"Cells"];
When I am going further for Cells and results it is giving me Empty element Error,
After referring to this post JSON parsing using NSJSONSerialization in iOS, it seems like "(" means an array in the response, but it is not working for me. Can someone help me, please?
results is an array, not a dictionary, so you cannot access its contents by name. Your JSON doesn't look well formed, though, because Key should be a string ("Title" not Title).
Each element in the results array is a dictionary, so to get the Value that corresponds to Title you can use
NSArray *results=jsonObject[#"Table"][#"Rows"][#"results"];
NSDictionary *result=[results objectAtIndex:0]; // access the first result
for (NSDictionary *result in results) {
if ([result[#"Key"] isEqualToString:#"Title"]) {
NSLog(#"The value of Title is %#",result[#"Value"]);
break;
}
}

JSon parsing error IOS with empty object key

Hi I have this JSON I'm trying to parse using NSDictionary and trying to get the values as mentioned . but the problem is i do not get a key when i further go into the JSON is there any way to remove this key to go more deep.
NSDictionary *Allinfo = [json objectForKey:#"Collection"];//I go into "Collection"
NSLog(#"All with response array: %#", Allinfo);
NSDictionary *datainfo = [Allinfo objectForKey:#"contact"];//i go into "contact"
after which i get
Data : (
{
attributeList = {
attribute = (
{
name = "display-name";
value = "tel:+";
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
},
{
attributeList = {
attribute = (
{
name = "display-name";
value = bob;
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
}
)
This starts from a { and i do not get a key for the next object so that i can get the values inside the JSOn
Is there any easier way to remove this or any other so that i can get values like name and value and store them in an array.
Thanks in advance
You have keys for all.
In fact you seem to get confused on array which is a part of attribute.
The outermost key is Data which contains array.
For each object of the array you have :
The first key is attributeList & contactD.
The value of attribute key is an array of 3 values. Each array contains key value pairs. keys are name & value.
I am not sure from where you got [Allinfo objectForKey:#"contact"]. Try to parse like below..
NSDictionary *Allinfo = [json objectForKey:#"Collection"];
NSArray *dataArray = [Allinfo objectForKey:#"Data"];
for(NSDictionary *dic in dataArray)
{
NSDictionary *attributeList=[dic objectForKey:#"attributeList"];
NSArray *attributeArray=[attributeList objectForKey:#"attribute"];
NSString *resourceURLString=[attributeList objectForKey:#"resourceURL"];
NSString *contactIdString=[dic objectForKey:#"contactId"];
for(NSDictionary *attributeDic in attributeArray)
{
NSString *nameString=[attributeDic objectForKey:#"name"];
NSString *valueString=[attributeDic objectForKey:#"value"];
}
}
You can use the following method for this
NSError *e = nil;
NSArray *itemArray = [NSJSONSerialization JSONObjectWithData:[response dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (!itemArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in itemArray) {
//Your Data
}
}

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

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.

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