NSData *urlDatat = [NSData dataWithContentsOfURL: [NSURL URLWithString:stringURL]];
NSDictionary* json1 = [NSJSONSerialization JSONObjectWithData:urlDatat options:0 error:&error];
NSString *urlDataString =[[NSString alloc] initWithData:urlDatat encoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlDatat options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments|NSJSONReadingMutableLeaves error:&error];
Both json1 and json return null. Actual JSON data from the server is ={"statusCode":"1","message":"success","utcMilliSeconds":"1501953923847"}
try to use
NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:urlDatat options:NSJSONReadingMutableLeaves error:&error];
UPDATED
NSURL *url = [NSURL URLWithString:#"https://api.kidstriangle.com/KTStandaloneAPI/Common/GetUtcMilliSeconds"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
Related
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];
I Converted NSData to string then I am getting the string like below, Now I want to parse this one. If parse with json serilazation I am getting json data nil.
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><EmployeesLoginMethodResponse xmlns="http://tempuri.org/"><EmployeesLoginMethodResult>[{"sms":"You have logged in successfully!","userId":"29","type":"1","name":"mng 56 78"}]</EmployeesLoginMethodResult></EmployeesLoginMethodResponse></soap:Body></soap:Envelope>
If I parse using XML I am Getting The String Like below,In this How to get value of sms,userId,name
[{
"sms": "You have logged in successfully!",
"userId": "13",
"type": "1",
"name": "Suhashini Kumari Singh"
}]
Here is my code
NSString *urlString=[NSString stringWithFormat:#"http://workforce.wifisocial.in/WebServicesMethods/EmployeesWebService.asmx"];
NSString* webStringURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString* requestBody =[NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><EmployeesLoginMethod xmlns=\"http://tempuri.org/\"><username>\%#</username><password>\%#</password><IpAddress>\%#</IpAddress><deviceName>\%#</deviceName></EmployeesLoginMethod></soap:Body></soap:Envelope>",self.userNameTextFiled.text,self.passwordTextField.text,ipAddress,deviceName];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[request setValue:#"\"http://tempuri.org/EmployeesLoginMethod\"" forHTTPHeaderField:#"SOAPAction"];
[request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]] ;
NSError *error;
NSHTTPURLResponse *response = nil;
NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
NSString* responseString = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"%#",responseString);
if (urlData)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
Please try XMLDictionary library. For more reference https://github.com/nicklockwood/XMLDictionary
Just convert your NSData to NSDictionary using XMLDictionary as below
NSDictionary *xmlDictionary = [NSDictionary dictionaryWithXMLData:returnData];
If you got you response in json string then try like below,
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
here responseString is final output json string that you have posted in question.
Then fetch data from json dictionary.
If this scenario will not work then take a look at NSXMLParser, you can refer Appcoda's tutorial.
It's nil because it's not the JSON parsing that's failing but because of the conditional type cast of the resulting object as a dictionary.
It's an array with one item which is dictionary. So, during parsing cast it as a NSArray.
Like,
Instead of:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
Use:
NSArray *arrJson=[NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSDictionary *json = [arrJson objectAtIndex:0];
NSString *sms=[json valueForKey:#"sms"];
NSString *userId=[json valueForKey:#"userId"];
NSString *type=[json valueForKey:#"type"];
NSString *name=[json valueForKey:#"name"];
You can use XML to JSON converter (XMLReader)
: https://github.com/amarcadet/XMLReader
#import "XMLReader.h"
Here is the sample snippet for your code :
NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (urlData)
{
NSDictionary *dict = [XMLReader dictionaryForXMLData:urlData error:&error];
NSLog(#"-----%#-----",dict);
NSError *jsonError;
NSString *json2 = [[[[[[dict valueForKey:#"soap:Envelope"] valueForKey:#"soap:Body"] valueForKey:#"EmployeesLoginMethodResponse"] valueForKey:#"EmployeesLoginMethodResult"] valueForKey:#"text"] stringByReplacingOccurrencesOfString:#"\"" withString:#"\""];
NSData *objectData1 = [json2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:objectData1 options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"-----%#-----",json1);
}
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"];
}
}
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 ?
I meet a problem to parse a jSON, I've a jSON like that :
{
"id": 0,
"message": "ok"
}
I tried several things to try to get the value of "id", and "message", but I've always an error..
How can I do to pick the value of "id", and "message" please ?
(I get the result of my JSON in a NSMutableArray)
EDIT :
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSMutableDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:publicTimeline.allKeys];
[sortedArray sortUsingSelector:#selector(localizedStandardCompare:)];
return sortedArray;
Your JSON string represents a dictionary. So you have to use NSDictionary instead of NSArray.
EDIT I
// convert dictionary into JSON
NSDictionary *fromDict = #{#"id": #(0), #"message": #"ok"};
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:fromDict options:0 error:nil];
// convert data (like you get from an API request) to dictionary
NSDictionary *toDict = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
Try this,
Parse the JSON response to NSDictionary
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *message = [responseDictionary valueForKey:#"message"];
I think its helpful to you (In this response you get first dictionary and dictionary contains two key.so )
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSString *message = [publicTimeline valueForKey:#"message"];
I Think it useful link for you. json parser