NSJSONSerialization JSON parsing issue - ios

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"]

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;
}

Remove extra spaces and new lines from JSON

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];

Using POST for flight API

I have been trying to implement the Wego flights API from http://support.wan.travel/hc/en-us/articles/200191669 which uses HTTP POST requests. I've only really ever used GET requests, so I did some reading on POST and so far I have not been able to find a way to post a request with a dictionary of flight data (in objective-c) as shown in the link above:
POST api.wego.com/flights/api/k/2/searches
{
"trips": [
{
"departure_code": "SYD",
"arrival_code": "LON",
"outbound_date": "2014-01-24",
"inbound_date": "2014-01-29"
}
],
"adults_count": 1
}
Do I have to create the NSDictionary myself and then (assign?) it to the request, or is there a way to format the dictionary into a string? Thanks in advance for any help :)
You have to create the POST data as follows:
NSDictionary *trips = [NSDictionary dictionaryWithObjectsAndKeys:
#"SYD", #"departure_code",
#"LON", #"arrival_code",
#"2014-01-24", #"outbound_date",
#"2014-01-29", #"inbound_date",
nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:
trips, #"trips",
#"1", #"adults_count",
nil];
NSError *jsonError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&jsonError];
And then make the POST request:
NSURL *url = [[NSURL alloc] initWithString:#"http://api.wego.com/flights/api/k/2/searches"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];
[urlRequest setHTTPMethod:#"POST"];
const char *parameters = [jsonData bytes];
NSData *postData = [[NSData alloc] initWithBytes:parameters length:strlen(parameters)];
[urlRequest setHTTPBody:postData];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&requestError];
NSLog(#"%#", [NSString stringWithUTF8String:[data bytes]]);

iOS parse specific jSON

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

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