JSON Parsing Issue - ios

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;
}
}

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

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 get the value from the NsDictionary

I am trying to get the value from the dictionary but its giving me null. Actually I have parsed the XML and then convert it to the dictionary Following is the dictionary after conversion :(I got it in log)
dictionary: {
"soap:Envelope" = {
"soap:Body" = {
GetServerStatusResponse = {
GetServerStatusResult = {
text = "<NewDataSet>\n <Table1>\n <ServerStatus>Standby</ServerStatus>\n </Table1>\n</NewDataSet>";
};
xmlns = "http://tempuri.org/";
};
};
"xmlns:soap" = "http://schemas.xmlsoap.org/soap/envelope/";
"xmlns:xsd" = "http://www.w3.org/2001/XMLSchema";
"xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance";
};
}
now I want to take the value from the ServerStatus tag. That is in this case , "StandBy".
But I am getting the null value in response. Please help? Is there a problem of spaces?
There is no key "ServerStatus" in your dictionary.
The only key is "soap:Envelope"
and "soap:Body", "xmlns:soap", "xmlns:xsd" and "xmlns:xsi" are keys of the dictionary corresponding to the key "soap:Envelope".
You can't access easily to "ServerStatus", what you can do is acceding to text and then parse the value associated to retrieve "ServerStatus"
You should be able to get the value in text this way :
[[[[[dictionary objectForKey:#"soap:Envelope"] objectForKey:#"soap:Body"] objectForKey:#"GetServerStatusResponse"] objectForKey:#"GetServerStatusResult"] objectForKey:#"text"];
You can get to the text in GetServerStatusResult using the following code:
NSDictionary *soapEnvelope = [dictionary valueForKey:#"soap:Envelope"];
NSDictionary *soapBody = [soapEnvelope valueForKey:#"soap:Body"];
NSDictionary *statusResponse = [soapBody valueForKey:#"GetServerStatusResponse"];
NSDictionary *statusResult = [statusResponse valueForKey:#"GetServerStatusResult"];
NSString *xmlString = [statusResult valueForKey:#"text"];
NSDictionary *textDictionary = [XMLDictionary dictionaryWithXMLString:xmlString];
Now the xml in text key is converted to NSDictionary and you can easily get the value of ServerStatus

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.

Resources