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);
}
Related
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;
}
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];
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 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
I have a problem with parsing JSON.
Here's my code:
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/lookup?bundleId=com.clickgamer.AngryBirds"]; //This URL only for testing
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *jsonParsingError = nil;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data = %# ", [[jsonArray objectForKey:#"results"] valueForKey:#"version"]);
}];
In Console it prints out: Data = (
"3.4.1"
)
But I want to have: Data = 3.4.1 What am I doing wrong?
seems valueForKey:#"version" returns an array with only one element.
try this:
NSLog(#"Data = %# ", [[[jsonArray objectForKey:#"results"]
valueForKey:#"version"]
objectAtIndex:0]);
try this:
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
If you try curl http://itunes.apple.com/lookup?bundleId=com.clickgamer.AngryBirds on the command line you can see from the output that the "results" object is an array so when you invoke the valueForKey method on the results array you get an array of all the #"version" keys in that array.
Example:
NSDictionary *test = #{#"results": #[#{#"version":#"1.0"}, #{#"version":#"2.0"}]};
NSLog(#"output: %#", [[test objectForKey:#"results"] valueForKey:#"version"]);
Output:
output: (
"1.0",
"2.0"
)
What you have to do is get the first object in the "results" array and get the version object from that eg.:
test[#"results"][0][#"version"]