can some pne please help me in optimize this code:
- (NSMutableDictionary *) parseResponse:(NSData *) data {
NSString *myData = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"JSON data = %#", myData);
NSError *jsonParsingError = nil;
//parsing the JSON response
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonParsingError];
if (jsonObject != nil && jsonParsingError == nil)
{
//NSLog(#"Successfully deserialized...");
NSLog(#"json object is %#",jsonObject);
if([jsonObject isKindOfClass:[NSDictionary class]])
{
NSLog(#"It has only dictionary so simply read it");
}
else if([jsonObject isKindOfClass:[NSArray class]])
{
NSLog(#"It has only NSArray so simply read it");
}
else if([jsonObject isKindOfClass:[NSString class]])
{
NSString *stringWithoutOpenCurly = [jsonObject stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSString *stringWithoutOpenAndCloseCurly = [stringWithoutOpenCurly stringByReplacingOccurrencesOfString:#"}" withString:#""];
NSArray *arrayOfKeyValue = [stringWithoutOpenAndCloseCurly componentsSeparatedByString:#","];
NSString *statusString = [arrayOfKeyValue objectAtIndex:0];
NSArray *statusKeyValueArray = [statusString componentsSeparatedByString:#":"];
NSString *statusKey, *statusValue;
statusKey = [[statusKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
statusValue = [[statusKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *messageString = [arrayOfKeyValue objectAtIndex:1];
NSArray *messageKeyValueArray = [messageString componentsSeparatedByString:#":"];
NSString *messageKey, *messageValue;
messageKey = [[messageKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
messageValue = [[messageKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *dataIdString = [arrayOfKeyValue objectAtIndex:2];
NSArray *dataIdKeyValueArray = [dataIdString componentsSeparatedByString:#":"];
NSString *dataIdKey, *dataIdValue;
dataIdKey = [[dataIdKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
dataIdValue = [[dataIdKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *nextString = [arrayOfKeyValue objectAtIndex:3];
NSArray *nextKeyValueArray = [nextString componentsSeparatedByString:#":"];
NSString *nextKey, *nextValue;
nextKey = [[nextKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
nextValue = [[nextKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *b64String = [arrayOfKeyValue objectAtIndex:4];
NSArray *b64KeyValueArray = [b64String componentsSeparatedByString:#":"];
NSString *b64Key, *b64Value;
b64Key = [[b64KeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
b64Value = [[b64KeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *fileNameString = [arrayOfKeyValue objectAtIndex:5];
NSArray *fileNameKeyValueArray = [fileNameString componentsSeparatedByString:#":"];
NSString *fileNameKey, *fileNameValue;
fileNameKey = [[fileNameKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
fileNameValue = [[fileNameKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSMutableDictionary *responseDictionary = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:statusValue, messageValue, dataIdValue, nextValue, b64Value, fileNameValue, nil] forKeys:[NSArray arrayWithObjects:statusKey, messageKey, dataIdKey, nextKey, b64Key, fileNameKey, nil]];
NSLog(#"manually created dictionary is ++++++++++++++++++++++++++++++%#",responseDictionary);
NSLog(#"statusValue is ++++++++++++++++++++++++++++++%#",[responseDictionary valueForKey:statusKey]);
return responseDictionary;
}
}
else //previoucly no else handler so put it here
{
// mErrorMessage = #"Server Error";
// [self stopIndicatorProgressWithError];
}
}
jsonObject is true for NSString class only???? do not know what's problem.
Any Help?
thanks & regards.
You can "optimize" your code by using the appropriate Foundation classes:
NSString *jsonObject = ...; // your JSON data as string
NSData *jsonData = [jsonObject dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:0 error:&error];
or, if you really need a mutable dictionary:
NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
Related
I have JSON format requirement something like this.
{
"first_name" : "XYZ",
"last_name" : "ABC"
}
I have values in NSString.
NSString strFName = #"XYZ";
NSString strLName = #"ABC";
NSString strKeyFN = #"first_name";
NSString strKeyLN = #"last_name";
And I use NSMutableDictionary
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
then output is
{
first_name = XYZ,
last_name = ABC
}
So I don't want "=" separating key & values instead I want ":" to separate key and values
I have went most of the stack overflow questions but didn't help getting "=" only in output
So please any help ?
Here is your answer :
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSInteger number = 15;
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSString *numValue = #"Number";
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:strFName forKey:strKeyFN];
[dic setObject:strLName forKey:strKeyLN];
[dic setObject:[NSNumber numberWithInt:number] forKey:numValue];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dic] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON %#",jsonString);
You write this code after your NSDictionary
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSDictionary *ictionary = [NSDictionary dictionaryWithObjectsAndKeys:
strKeyFN, strFName,strKeyLN, strLName,nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary as string:%#", jsonString);
NSString *strFName = #"ABC";
NSString *strLName = #"XYZ";
NSString *strKeyFN = #"last_name";
NSString *strKeyLN = #"first_name";
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dict] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStrng = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Your required JSON is %#",jsonStrng);
try this:-
NSString *cleanedString1 =[strFName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSString *cleanedString2 =[strLName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:
cleanedString1, strKeyFN,
cleanedString2, strKeyLN,nil];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
this very robust code to achieve you goal
NSDictionary *userDic = #{strKeyFN:strFName,strKeyLN:strLName};
you have to convert NSMutableDictionary into NSData
then convert the NSData Into json string you want
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jasonString= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}
I am trying to parse an NSString to NSArray but couldn't get any success. Here is my String: NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
I want this string mapped to NSArray.
NSArray *tempArray = points;
OK, code golf (untested):
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSArray *point in pointsArray) {
NSAssert([point count] == 2, #"Invalid point");
// do thing with point
CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}
Can you plz try this, May it solve your problem,
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:#","];
NSLog(#"%#",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];
NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
[yourarray addObject:[NSString stringWithFormat:#"%#,%#",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(#"%#",yourarray);
Happy Coding!!
That string looks like JSON so you can use NSJSONSerialization
NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
I made the coding of getting weather application response.I could not get the exact latitude,longitude and population value.Instead of exact value i am getting response as a null.After that i cant get the other response.Also the response is-> " Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' "
Something i have done wrong in array index format.So anyone help me to get all values?
This is my coding
.M part
-(void)viewDidLoad
{
[super viewDidLoad];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"POST"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *dict1 =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
//NSDictionary *dict1a =[dict1 objectForKey:#"JSON"];
NSDictionary *dict2 = [dict1 objectForKey:#"search_api"];
NSArray *array1 =[dict2 objectForKey:#"result"];
for(int i=0;i<[array1 count]; i++)
{
NSDictionary *dict3 =[array1 objectAtIndex:i];
NSArray *array2 =[dict3 objectForKey:#"areaName"];
NSDictionary *dict4 =[array2 objectAtIndex:i];
// NSArray *arr3 =[dict4 objectForKey:#"London"];
//manage.transformName= [NSString stringWithFormat:#"%#",[venueNem objectForKey:#"username"]];
NSString *str1= [NSString stringWithFormat:#"%#",[dict4 objectForKey:#"value"]];
NSLog(#"the response ==%#",str1);
NSArray *array3 =[dict3 objectForKey:#"country"];
NSDictionary *dict5 =[array3 objectAtIndex:i];
NSString *str2 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"value"]];
NSLog(#"the response ==%#",str2);
NSString *str3 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str3);
NSString *str4 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str4);
NSString *str5 = [NSString stringWithFormat:#"%#",[dict5 objectForKey:#"population"]];
NSLog(#"the response ==%#",str5);
NSArray *arr4 =[dict3 objectForKey:#"region"];
NSDictionary *dict6 =[arr4 objectAtIndex:i];
NSString *str6 = [NSString stringWithFormat:#"%#",[dict6 objectForKey:#"value"]];
NSLog(#"the response ==%#",str6);
NSArray *arr5 =[dict3 objectForKey:#"weatherUrl"];
NSDictionary *dict7 =[arr5 objectAtIndex:i];
NSString *str7 =[NSString stringWithFormat:#"%#",[dict7 objectForKey:#"value"]];
NSLog(#"the response ==%#",str7);
}
for(int j=0;j<[array1 count];j++)
{
NSDictionary *dict8 =[array1 objectAtIndex:j];
NSArray *arr6 =[dict8 objectForKey:#"areaname"];
NSDictionary *dict9 =[arr6 objectAtIndex:j];
NSString *str8 =[NSString stringWithFormat:#"%#",[dict9 objectForKey:#"value"]];
NSLog(#"the response ==%#",str8);
NSArray *arr7 =[dict8 objectForKey:#"country"];
NSDictionary *dict10 =[arr7 objectAtIndex:j];
NSString *str9 =[NSString stringWithFormat:#"%#",[dict10 objectForKey:#"value"]];
NSLog(#"the response ==%#",str9);
NSString *str10 =[NSString stringWithFormat:#"%f",[dict10 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str10);
NSString *str11 =[NSString stringWithFormat:#"%f",[dict10 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str11);
NSString *str12 =[NSString stringWithFormat:#"%d",[dict10 objectForKey:#"population"]];
NSLog(#"the response ==%#",str12);
NSArray *arr8 =[dict8 objectForKey:#"region"];
NSDictionary *dict11 =[arr8 objectAtIndex:j];
NSString *str13 =[NSString stringWithFormat:#"%#",[dict11 objectForKey:#"value"]];
NSLog(#"the response ==%#",str13);
NSArray *arr9 =[dict8 objectForKey:#"weatherurl"];
NSDictionary *dict12 =[arr9 objectAtIndex:j];
NSString *str14 =[NSString stringWithFormat:#"%#",[dict12 objectForKey:#"value"]];
NSLog(#"the response ==%#",str14);
}
NSDictionary *dict13 =[array1 objectAtIndex:2];
NSArray *arr10 =[dict13 objectForKey:#"areaname"];
NSDictionary *dict14 =[arr10 objectAtIndex:2];
NSString *str15 =[NSString stringWithFormat:#"%#",[dict14 objectForKey:#"value"]];
NSLog(#"the response ==%#",str15);
NSArray *arr11 =[dict13 objectForKey:#"country"];
NSDictionary *dict15 =[arr11 objectAtIndex:2];
NSString *str16 =[NSString stringWithFormat:#"%#",[dict15 objectForKey:#"value"]];
NSLog(#"the response ==%#",str16);
NSString *str17 =[NSString stringWithFormat:#"%f",[dict15 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str17);
NSString *str18 =[NSString stringWithFormat:#"%f",[dict15 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str18);
NSString *str19 =[NSString stringWithFormat:#"%d",[dict15 objectForKey:#"population"]];
NSLog(#"the response ==%#",str19);
NSArray *arr12 =[dict13 objectForKey:#"region"];
NSDictionary *dict16 =[arr12 objectAtIndex:2];
NSString *str20 =[NSString stringWithFormat:#"%#",[dict16 objectForKey:#"value"]];
NSLog(#"the response ==%#",str20);
NSArray *arr13 =[dict13 objectForKey:#"weatherurl"];
NSDictionary *dict17 =[arr13 objectAtIndex:2];
NSString *str21 =[NSString stringWithFormat:#"%#",[dict17 objectForKey:#"value"]];
NSLog(#"the response ==%#",str21); }
Look at you first FOR loop. I am not saying the error is in only there.
EDIT
for(int i=0;i<[array1 count]; i++)
{
NSDictionary *dict3 =[array1 objectAtIndex:i];
NSArray *key = [dict3 allKeys];
for (int j = 0; j < key.count ; j++) {
if ([[key objectAtIndex:j] isEqualToString:#"areaName"]) {
NSArray *array2 =[dict3 objectForKey:#"areaName"];
//Area name
NSString *area = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"country"]){
NSArray *array2 =[dict3 objectForKey:#"country"];
//Country
NSString *country = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"latitude"]){
//Latitude
NSString *latitude = [dict3 objectForKey:#"latitude"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"longitude"]){
//longitude
NSString *longitude = [dict3 objectForKey:#"longitude"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"population"]){
//population
NSString *population = [dict3 objectForKey:#"population"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"region"]){
NSArray *array2 =[dict3 objectForKey:#"region"];
//region
NSString *region = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"weatherUrl"]){
NSArray *array2 =[dict3 objectForKey:#"weatherUrl"];
//weatherUrl
NSString *weatherUrl = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
}
}
arra=[[NSMutableArray alloc]init];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:#"search_api"]objectForKey:#"result"];
for (int i=0; i<[array count]; i++) {
NSLog(#"the areaName==%#",[[[[array objectAtIndex:i]objectForKey:#"areaName"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the country==%#",[[[[array objectAtIndex:i]objectForKey:#"country"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the latitude==%#",[[array objectAtIndex:i]objectForKey:#"latitude"]);
NSLog(#"the long==%#",[[array objectAtIndex:i]objectForKey:#"longitude"]);
NSLog(#"the pop==%#",[[array objectAtIndex:i]objectForKey:#"population"]);
NSLog(#"the region==%#",[[[[array objectAtIndex:i]objectForKey:#"region"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the url==%#",[[[[array objectAtIndex:i]objectForKey:#"weatherUrl"]objectAtIndex:0]objectForKey:#"value"]);
NSString *areaName=[[[[array objectAtIndex:i]objectForKey:#"areaName"]objectAtIndex:0]objectForKey:#"value"];
[arra addObject:areaName];
}
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.