Remove extra spaces and new lines from JSON - ios

Below is my code, and am trying to parse a JSON; I am getting response but when am printing dictionary, it's null.
below is the response string, result of JSON.
NSString *post = [[NSString alloc] initWithFormat:#"jobid=%#",idjob];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:#"URL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"login:%#",str);
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"aarraa:%#",jsonDict);
Response for str :
{"Jobdesc":[{"jobid":"11260","job_title":"Linux + Nagios System Administrator","job_desc":"<p>Technical skills required:</p>
<ol>
<li>Should be ready to work during French timings</li>
<li>Linux Certification / training is a must</li>
<li>Linux System administration (Red hat Linux, CentOS Servers)</li>
<li>Experience in LAMP configuration and troubleshooting</li>
<li>Knowledge on windows OS</li>
<li>Experience on monitoring tools like Nagios / Centreon, Ops5</li>
<li>Scripting in Shell, Perl or Python</li>
</ol>
","job_role":"Linux + Nagios System Administrator","job_exp":"1-5 year","job_education":"Others","job_location":"Delhi","job_address":"Delhi","job_company_name":"Pandya Business Solutions.","job_company_url":"http://www.pandyabusinesssolutions.com/","job_company_email":"singhjapesh#gmail.com","job_status":""}]}
but parameter jsonDict is null.

Try this...
NSString *jsonString = [NSString stringWithFormat:#"URL"];
NSURL *nurl = [NSURL URLWithString:jsonString];
NSData *jsonData = [NSData dataWithContentsOfURL:nurl];
NSError *error = nil;
NSDictionary *dictResult = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];

It seems that you are trying to serialise your data just before you completely get it, below is the code with completionHandler which will begin further process once you get all your data, so try this:
[NSURLConnection sendAsynchronousRequest: theRequest queue [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
}];

i tried validating JSON response, and found that there were extra spaces in JSON so below is my resolved answer.
NSString *post = [[NSString alloc] initWithFormat:#"jobid=%#",idjob];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:#"http://ncrjobs.in/webservice/jobdesc.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSCharacterSet *spaces=[NSCharacterSet whitespaceCharacterSet];
NSPredicate *predicates=[NSPredicate predicateWithFormat:#"SELF !=''"];
NSArray *temparray=[[str componentsSeparatedByCharactersInSet:spaces]filteredArrayUsingPredicate:predicates];
str=[temparray componentsJoinedByString:#" "];
NSString *string = [str stringByReplacingOccurrencesOfString:#"[\r\n]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, str.length)];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];

Serialize data like this.
NSMutableDictionary *json =[NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];

Related

iOS Convert NSData to NSDictionary returns nil?

In My code I want to convert NSData to NSDictionary but it returns nil I don't know what mistake I made,I Used NSJSONSerialization for convert data to dictionary, The NSData was received from server response.
Here I show my Full code what I am trying.
-(void)SendPushNotification:(NSString*)getUrl :(NSMutableDictionary *)getData withCompletionBlock:(void(^)(NSDictionary *))completionBlock
{
NSError *error;
NSLog(#"dict val: %#",getData);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:getData options:NSJSONWritingPrettyPrinted error:&error];// Pass 0 if you don't care about the readability of the generated string
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLengthas = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:getUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSString *chkRegDevice= [[NSUserDefaults standardUserDefaults] stringForKey:#"bearer"];
NSString *strfds=[NSString stringWithFormat:#"bearer %#",chkRegDevice];
[request setHTTPMethod:#"POST"];
[request setValue:postLengthas forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:strfds forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
if(error)
{
NSLog(#"%#", [error localizedDescription]);
completionBlock(nil);
}else{
NSError *jsonError;
NSString *clientDetail = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"clientDetail: %#", clientDetail);
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"json %#",json);
if (![clientDetail isEqualToString:#"Object reference not set to an instance of an object."]) {
if (completionBlock) {
completionBlock(json);
}
}
else
{
completionBlock(nil);
}
}
}];
[taskk resume];
}
Here the following response I get to convert NSData to NSString.
"{\"multicast_id\":8856529321585625357,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1534479035021563%1dbdaa031dbdaa03\"}]}"
Pass NSData object(data) directly to JSONObjectWithData.
Also, to check the error, you can print jsonError.
Try the following code:
NSError* error;
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa
options:kNilOptions
error:&error];
NSLog(#"JSON DICT: %#", json);
Try this.
NSString* str = your string data;
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *decodeString = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
NSDictionary *dict = [self dictionaryWithJsonString:decodeString];
/////////////////////
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
return nil;
}
return dic;
}

NSJSONSerialization get error "index 1 beyond bounds for empty array"

sometimes I get error "index 1 beyond bounds for empty array" at this line
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This is my full code
+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
return json;
}
Sometimes I get error, Sometimes not. I don't understands ? please help me, thanks everyone.
Whenever you get an error like the above, try the following:
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
if (error)
{
//1. See what the error says
NSLog(error.localizedDescription);
//2. Convert the original data into a string
NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];
//Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
cachePolicy: defaultCachePolicy
timeoutInterval: defaultTimeoutInSeconds];
plz change your cachePolicy with defaultCachePolicy and try :)

find cell tower location in iOS

Now I m trying to find the tower location using cellID, MNC,MCC and LAC.
If you have the cellId, MNC,MCC and LAC then you can easily find the cell tower location in iOS. after some struggle i get the ans of this problem.
now this is the ans of this question.
#define google_geo_location #"https://www.googleapis.com/geolocation/v1/geolocate?key="
google API LOCATION
NSString * urlString = [NSString stringWithFormat:#"google API key ",google_geo_location];
Create JSON STRING
NSString *json=[NSString stringWithFormat:#"[{\"homeMobileCountryCode\": \"%#\",\"homeMobileNetworkCode\": \"%#\",\"cellTowers\": [{\"cellId\": \"%#\",\"locationAreaCode\": \"%#\",\"mobileCountryCode\": \"%#\",\"mobileNetworkCode\": \"%#\" }]}]",_mcctext,_mnctext,_cellidtext,_lactext,_mcctext,_mnctext];
convert JSON STRING in to JSON DICTIONARY
NSError *jsonError;
NSData *objectData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsondic = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
Create url from string
NSURL *urlStr=[NSURL URLWithString:urlString];
if (urlStr == nil)
{urlStr = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:urlStr];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
set request body, If method type is "POST" use only POST
NSData *data=[NSJSONSerialization dataWithJSONObject:jsondic options:NSUTF8StringEncoding error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString.....%#",jsonString);
NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
// for set requestBody
[request setHTTPBody:requestBody];
now you get response from server
NSHTTPURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSMutableDictionary *resultantDict;
if (responseData != nil)
{
resultantDict=[NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(#"resultantDict=%#",resultantDict);
NSString *errorCode=#"";
NSString *errorMessage=#"";
if ([[resultantDict allKeys] containsObject:#"error"])
{
errorCode=[NSString stringWithFormat:#"%#", [[resultantDict valueForKey:#"error"]valueForKey:#"code"]];
errorMessage= [[resultantDict valueForKey:#"error"]valueForKey:#"message"];
}
}

responseString from json parse nil

I want to parse a json from an url given by soundcloud.
NSURL *url = [NSURL URLWithString:test[indexPath.row]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSData* jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary* allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
Url has this form:
https://api.soundcloud.com/tracks/195677713/stream?client_id=3e6cb435319c6fdaad56ff5641e0f89e
but responseString is nil .
Any ideea why ?

NSInvalidArgumentException', reason: 'data parameter is nil

Some time when I call this piece of code *data is nil. It works most of the times except for certain situations which I'm not able to find.
Does anyone know why data could be nil and under which circumstances it could happen?
Some times *data isn't nil but it isn't what I'm expecting (for example I'm getting "login_okit_IT" instead of "login_ok")
Here is the code:
+ (NSDictionary *)eseguiRichiestaConURL:(NSString *)urlScript
{
NSString *rawStr = [NSString stringWithFormat:#""];
NSData *data = [rawStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlScript];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
//[request setTimeoutInterval:10000];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"%#", responseData);
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"%#", responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
if(responseData == nil)
NSLog(#"------ PARAMETRI VUOI -------");
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
return dict;
}
Thanks in advance.

Resources