Mrugesh Tank Mrugesh Tank - 6 months ago 16
JSON Question

Fetch data using JSON parsing via post method in iOS7 using NSJsonSerialization

I am new to iOS Development. Need help to parse this data using NSJSONSerialization. Data comes via post method.
Data is like this
[
{
"edition_id": "1",
"error": false,
"long_name": "Rajkot",
"message": "RESULT_OK",
"short_name": "RJT"
}
]

and code of my file is like this

NSURL *theURL = [NSURL URLWithString:@"MYURL"];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setURL:theURL];
[theRequest setHTTPMethod:@"POST"];
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theRequest]];
NSError *error;
NSMutableDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:kNilOptions error:&error];

Answer
NSString * uid = @"2"; // variable value
NSString *post = [NSString stringWithFormat:@"uid=%@",uid]; // post variable
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://localhost/my/json_post/index.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
/* NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(@"json Reply : %@", theReply);
*/

NSArray *arr = [NSJSONSerialization JSONObjectWithData:POSTReply options:0 error:nil];
NSLog(@"%@",arr);

NSLog(@"%@",[arr valueForKey:@"id"]); //this is table column name
NSLog(@"%@",[arr valueForKey:@"name"]);
NSLog(@"%@",[arr valueForKey:@"surname"]);