Can't iterate JSON string from asp.net WCF service in Xcode - ios

I am new to objective-c but I am trying to render out a simple UItableview, filling it with data from my REST service coded in asp.net. The service takes data from SPs run on SQL servicer and using the JSONSerailzer class spits out a JSON string. I have verified it is a valid JSON string by pasting the output to an online JSON viewer.
Example as follows (This is exactly how my service returns it):
{"d":"[{\"callref\":12345,\"user\":\"foo\",\"name\":\"bar\"},{\"callref\":54321,\"user\":\"bar\",\"name\":\"foo\"}]"}
I can get the data in to objective-c fine via:
id result = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
However when I try to step into this result either by casting as NSDictionary or NSArray but the result always ends up as NSCFString and because of that it crashes my code when I try to enter a for loop.
NSArray *allItems = [result objectForKey:#"d"];
for (int i=0; i<allItems.count; ++i) {
NSDictionary *item = [allItems objectAtIndex:i];
NSString *callref=[item objectForKey:#"callref"];
NSString *user=[item objectForKey:#"user"];
NSString *name=[item objectForKey:#"name"];
}
What am I missing here? Any help greatly appreciated! Thanks in advance.

The JSON being returned from the server is not what you expect it to be, by the look of it.
It's a dictionary (see the outer { and }), however it contains a key of "d" and a string value of "[{\"callref\" ..." (note the first double-quote and the escaped inner double-quotes).
So first job is to fix the server, which is off-topic to your question.
After that, it should be as simple as:
NSDictionary* result = [NSJSONSerialization JSONObjectWithData:webData
options:kNilOptions
error:&error];
NSArray *keys = [result allKeys];
for (NSString *key in keys) {
NSArray *array = result[key];
for (NSDictionary *item in array) {
NSString *callref = item[#"callref"];
NSString *user = item[#"user"];
NSString *name = item[#"name"];
}
}

Related

Parsing of JSON array returning blank array

I have an array which is of below kind.
{"Hotweeks":[{"Image":"http://www.example.com/wp-content/uploads/0970E01L.jpg","Description":"Ocean Shores, WA","PostTitle":"Windjammer Condominiums"},
{"Image":"","Description":"","PostTitle":"0970O01L"},
{"Image":"","Description":"","PostTitle":"0970I08L"},
{"Image":"","Description":"","PostTitle":"0970I06L"},
{"Image":"","Description":"","PostTitle":"0970I04L"},
{"Image":"","Description":"","PostTitle":"0970i03L"},
{"Image":"","Description":"","PostTitle":"0970I02L"},
{"Image":"","Description":"","PostTitle":"0970I01L"},
{"Image":"","Description":"","PostTitle":"0970E02L"},
{"Image":"","Description":"","PostTitle":"0970E01L"},
{"Image":"http://www.example.com/wp-content/uploads/0936E01L.jpg","Description":"Manson, WA","PostTitle":"Wapato Point"},
{"Image":"","Description":"","PostTitle":"0936O05L"},
{"Image":"","Description":"","PostTitle":"0936O04L"},
{"Image":"","Description":"","PostTitle":"0936O03L"},
{"Image":"","Description":"","PostTitle":"0936O02L"},
{"Image":"","Description":"","PostTitle":"0936O01L"},
{"Image":"","Description":"","PostTitle":"0936I01L"},
{"Image":"","Description":"","PostTitle":"0936E03L"},
{"Image":"","Description":"","PostTitle":"0936E02L"},
{"Image":"","Description":"","PostTitle":"0936E01L"}]}
Which I am trying to parse using the below code.
NSArray *array = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);
This is returning null in Nslog.
…"Description":"Ocean Shores, WA,"PostTitle":…
is missing a " after Ocean Shores, WA. It should be
…"Description":"Ocean Shores, WA","PostTitle":…
Use a JSON validator to check for this type of thing. There are many to pick from. I use the Chrome apps JSON Lint and JSON Editor.
The top level of your Json file is an object, not an array (it doesn't start with '['). That being said, if you check array's type like this: NSLog("%#", [array class] you'll probably see it's a NSDictionary.
To get the array you can do this:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSArray *array = jsonDict[#"Hotweeks"];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);

string handling in ios

I am getting String data from server in the format below. I want to get the value for every tag like phonenumber and name etc. I am able to convert it in array by comma separator. how to get individual values?
Company:Affiliated CO,Organization:TECHNICAL EDUCATION
SOCIETY,Organization:SINHGAD,Organization:National Basketball Association,Person:Parikshit N. Mahalle,PhoneNumber:81 98 22 416 316,PhoneNumber:9120-24100154,Position:Professor,SportsEvent:NBA.
Say your original string is stored in rawString.
You need to :
1) split the string by ,
NSArray *pieces = [rawString componentsSeparatedByString:#","];
2) for each item in this array, split it by :, and add it to a dictionary :
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSString *piece in pieces) {
NSArray *splitPiece = [piece componentsSeparatedByString:#":"];
// key is at splitPiece[0], value is at splitPiece[1]
dict[splitPiece[0]] = splitPiece[1];
}
Then you'll have a dictionary of what you wanted in the first place.
But as suggested in the comments, it would be far better (and more flexible) for you to receive JSON data.
Edit: your original string shows there are multiple fields named Organization. The code I've given is not designed to handle such cases, it's up to you to build upon it.
If this data is not being returned as a JSON object then you'll have to go with #Clyrille answer. But if it is JSON then NSJSONSerialization:JSONObjectWithData:options:error: will be the way to go.
EXAMPLE
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:/*urlResponse*/ options:0 error:nil];
NSString *company = [json objectForKey:#"Company"];
NSString *Organization = [json objectForKey:#"Organization"];
NSString *Person = [json objectForKey:#"Person"];
NSString *PhoneNumber = [json objectForKey:#"PhoneNumber"];
NSString *Position = [json objectForKey:#"Position"];
NSString *SportsEvent = [json objectForKey:#"SportsEvent"];

how to get string removing parameters [duplicate]

This question already has answers here:
Remove characters from NSString?
(6 answers)
Closed 8 years ago.
I am getting string from json dictionory but result string is in brackets, i have to get string without backets
code is
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dictResult = [jsonDictionary objectForKey:#"result"];
NSDictionary *dictPronunciations = [dictResult valueForKey:#"pronunciations"];
NSDictionary *dictAudio = [dictPronunciations valueForKey:#"audio"];
NSString *strMp3Path = [dictAudio valueForKey:#"url"];
NSLog(#"str mp3 path %#",strMp3Path);
and result is
(
(
"/v2/dictionaries/assets/ldoce/gb_pron/abate0205.mp3"
)
)
I want to get /v2/dictionaries/assets/ldoce/gb_pron/abate0205.mp3 as a string without brackets. Please help...
The object you are logging is not a NSString instance. it is a string inside an array in an array.
try:
NSLog(#"str mp3 path %#",strMp3Path[0][0]);
if this prints as desired, the object dictAudio holds with the key url is an array, with an array. you should fix that where ever you stick it into the dictionary.
Try with following code:
NSMutableArray *myArray = [dictAudio valueForKey:#"url"];
NSString *myStr = [[myArray objectAtIndex:0] objectAtIndex:0];
NSLog(#"%#", myStr);
Use this code. If your values are multiple from json then the value can be added one by one without braces :
NSMutableArray *dictPronunciations = [dictResult valueForKey:#"pronunciations"];
NSMutableArray *arrayPronunciations = [[NSMutableArray alloc] init];
for (int i = 0; i< [dictPronunciations count]; i++)
{
NSString *string = [dictPronunciations objectAtIndex:i];
NSLog(#"String = %#",string);
[arrayPronunciations addObject:string];
}
NSLog(#"Array Pronounciations = %#",arrayPronunciations);

SBJson displays null

I am trying to parse some json data with SBJson to show the current temperature. The example code from this tutorial works perfect: Tutorial: Fetch and parse JSON
When I change the code to my json feed i get a null. I am kind of new to JSON but followed every tutorial and documentation I found. The json source i used: JSON Source
My code with sbjson:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSArray* currentw = [(NSDictionary*)[responseString JSONValue] objectForKey:#"current_weather"];
//choose a random loan
NSDictionary* weathernow = [currentw objectAtIndex:0];
//fetch the data
NSNumber* tempc = [weathernow objectForKey:#"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:#"weatherCode"];
NSLog(#"%# %#", tempc, weatherCode);
and of course I have already implemented the other sbjson code.
There is no current_weather key in the JSON data you posted. The structure is:
{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }
Here's a visual representation:
Therefore, to get to temp_C, you'd need to first obtain the top-level data property:
NSDictionary* json = (NSDictionary*)[responseString JSONValue];
NSDictionary* data = [json objectForKey:#"data"];
then, from that, obtain the current_location property:
NSArray* current_condition = [data objectForKey:#"current_condition"];
and finally, from the current_location array, get the element you're interested in:
NSDictionary* weathernow = [current_condition objectAtIndex:0];
Also note that temp_C and weatherCode are strings, not numbers. To transform them to numbers, instead of:
NSNumber* tempc = [weathernow objectForKey:#"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:#"weatherCode"];
you could use something like:
int tempc = [[weathernow objectForKey:#"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:#"weatherCode"] intValue];
(or floatValue / doubleValue if the value is not supposed to be an int, but rather a float or a double)
You would then use %d (or %f for float / double) as a format string:
NSLog(#"%d %d", tempc, weatherCode);
Provided link returns json without current_weather parameter. There is only current_condition parameter, please review this.
Use NSJSONSerialization instead of JSONValue.
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"jsonDict:%#",jsonDict);
In your link, there is no current_weather key.
NSString* tempc = [[[[jsonDict objectForKey:#"data"] objectForKey:#"current_condition"] objectAtIndex:0] objectForKey:#"temp_C"];

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources