Parsing JSON Within JSON in Objective-C - ios

I'm trying to store the JSON that is within the JSON i get from the following request...
NSURL *URL = [NSURL URLWithString:#"http://www.demo.com/server/rest/login?username=admin&password=123"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
}];
[task resume];
The resulting JSON obtain from body is the following and as you can see there is a JSON within the JSON, how can I store that JSON in a NSDictionary as you can see that JSON is between quotation marks.
[
{
tag: "login",
status: true,
data:
"
{
"userID":1,
"name":"John",
"lastName":"Titor",
"username":"jtitor01",
"userEmail":"jtitor01#gmail.com",
"age":28,
}
"
}
]

What you have in reality:
Classic JSON, where inside there is a String "representing" a JSON.
So, since we can do:
NSData <=> NSString
NSArray/NSDictionary <=> JSON NSData
We just have to switch between them according to the kind of data we have.
NSArray *topLevelJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *lowLevelString = [[topLevelJSON firstObject] objectForKey:#"data"];
NSData *lowLevelData = [lowLevelString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *final = [NSJSONSerialization JSONObjectWithData:lowLevelData options:0 error:nil];

You should use this line of code
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:&errorJson];
it will help.thanks

Try this
- (void)loadDetails {
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
_allVehicleLocationsArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self afterCompleteDoThis];
}] resume];
}
- (void)afterCompleteDoThis {
for (NSDictionary *vehicleDict in _allVehicleLocationsArray) {
NSLog(#" PPP %#" , [vehicleDict valueForKey:#"vehicleType"]);
}
}

Related

How to add Dictionary as a Request Parameter For HTTPBody in NSJSONSerialization?

I am creating one demo Web Services Code without using AFNetworking Framework.
My HTTP Request Parameter in Dictionary.
How can I set it on HTTPBody?
MY Code is as follow
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl];
[request setHTTPMethod:#"POST"];
NSString *postString = "Request Parameter";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"requestReply: %#", requestReply);
NSError *jsonError;
NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];
You Can Do like that With AFnetworking and Without Af Networking.
NSString *stringUrl = #"xxx";
NSURLSessionConfiguration *myConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *myManager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:myConfiguration];
AFHTTPResponseSerializer *mySerilizer = [[AFHTTPResponseSerializer alloc]init];
[myManager setResponseSerializer:mySerilizer];
NSDictionary *param = [[NSDictionary alloc]initWithObjectsAndKeys:#"value==",#"Token", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *requestParameter = [NSDictionary dictionaryWithObject:string forKey:#"request"];
[manager POST:stringUrl parameters:requestParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *error;
if(!error)
{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"%#",dict);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
Without Dictionary
NSString *urlString = #"xxxx";
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:configuration];
AFHTTPResponseSerializer *serilizer = [[AFHTTPResponseSerializer alloc]init];
[manager setResponseSerializer:serilizer];
NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:#"value",#"key", nil];
[manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *error;
if(!error)
{
NSDictionary *finalData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Final Data is %#",finalData);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
Without AFNetworking
NSString *MyUrlString = #"xxxx";
NSURL *url = [NSURL URLWithString:MyUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = #"key=value";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];
Note:-Do not forget to put resume
Thank you
Check your condition with my working code,
NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:50.0];
[_request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"]; // Interact your backend developer for header
[_request addValue:#"application/json" forHTTPHeaderField:#"Accept"];// Interact your backend developer for header
[_request setHTTPMethod:#"POST"];
NSError *error;
NSData *_inputData = [NSJSONSerialization dataWithJSONObject:inputDictionary options:0 error:&error];
[_request setHTTPBody:_inputData];
NSURLSessionDataTask *_fetchData = [[[self class] session] dataTaskWithRequest:_request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(!error) {
NSError* error;
completionBlock(data,error,1);
} else {
completionBlock(data,error,0);
}
}];
[_fetchData resume];
Got The Data
NSURL *stringwithUrl = [NSURL URLWithString:#"XXXX"];
NSMutableURLRequest *requestUrl = [NSMutableURLRequest requestWithURL:stringwithUrl];
[requestUrl setHTTPMethod:#"POST"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"Value==",#"Key", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *mainString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *requestString = #"request=";
NSString *finalString = [requestString stringByAppendingString:mainString];
[requestUrl setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *sesion = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[sesion dataTaskWithRequest:requestUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",dict);
}]resume];

IOS: kCFErrorDomainCFNetwork error -1002. Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"

hello all i know this kind of question asked previously but i didn't get any solution from them
in my project i am working in login view when i am put code on login button i am getting an error
Error : Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x7fb37b62c9a0 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x7fb37b715a20 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1002.)"}
but i am using the same code for login which i used in my previous projects and it works fine there
here is my code:
-(IBAction)login:(id)sender
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php?token={LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUc4d0RRWUpLb1pJaHZjTkFRRUJCUUFEWGdBd1d3SlVBeWo0WE9JNjI4cnJRTG9YeEpXNG1zUWI1YmtvYk1hVQpzMnY1WjFKeXJDRWdpOVhoRzZlZk4rYTR0eGlMTVdaRXdNaS9uS1cyL1NCS2pCUnBYUzVGYUdiV0VLRG1WOXkvCkYrWHhsUXVoeER0MEV3YkRBZ01CQUFFPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K}&method=user.getLogin"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"login=abc#gmail.com&password=123456"];//,username.text, password.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"map data is = %#",mapData);
NSURLSessionDataTask * postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse* response, NSError * error) {
if(error == nil)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"jsondic= %#",jsonDic);
NSDictionary *userDataDic = [jsonDic objectForKey:#"data"];
NSLog(#"Dict is %#",userDataDic);
Please help me to resolve it i already see the similar type of questions but didn't overcome from this issue
Any help is appreciated
I tried your code.Except your url the other lines of code is correct.If you pass your corrct URL,it works perfectly.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php"]]; //pass your url here
[request setHTTPMethod:#"POST"];
//Passing The String to server
NSString *strUserId = #"pradeep.kumar#eyeforweb.com";
NSString *strPassword = #"admin123";
NSString *userUpdate =[NSString stringWithFormat:#"login=%#&password=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is %#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"The postData is - %#",data1);
//Apply the data to the body
[request setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];

NSURLSessionDataTask returning incorrect result

I have used following code for Posting request through NSURLSession, but it is returning incorrect result. but if I check it with POSTMAN with same parameters and url then it's working fine. Please help.
// URL of the endpoint we're going to contact.
NSURL *url = url;
// Create a simple dictionary with numbers.
NSDictionary *param = #{#"key1": #"value1"};
NSError *error = nil;
// Convert the dictionary into JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:param
options:kNilOptions error:&error];
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.HTTPBody = JSONData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (!error)
{
if (data) {
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
success(json);
}
else {
failure(error);
NSLog(#"******************* error in sendRequestToServer");
}
//NSLog(#"Status code: %i", ((NSHTTPURLResponse *)response).statusCode);
}
else {
failure(error);
NSLog(#"******************* error in sendRequestToServer");
}
}];
// Start the task.
[task resume];
I'd start by setting the Content-Type header. Most servers handle POST requests differently depending on the content type, and you aren't setting one.

How to Post JSON Data in synchronously way?

How to post JSON Data in synchronously way? Can use NSURLSession or AFNetworking or other way?
Sample basic code for posting data to server using synchronous
//PASS YOUR URL HERE
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"your URL"]];
//create the Method "POST" for posting data to server
[request setHTTPMethod:#"POST"];
//Pass The String to server like below
NSString *strParameters =[NSString strin gWithFormat:#"user_email=%#&user_login=%#&user_pass=%#& last_upd_by=%#&user_registered=%#&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
//Print the data that what we send to server
NSLog(#"the parameters are =%#", strParameters);
//Convert the String to Data
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
In user3182143's answer, sendSynchronousRequest is deprecated in latest version iOS 9.
You can use NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSString *strResult = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
}] resume];
Here is my solution:
- (IBAction)postJSONSynchronization:(id)sender {
__block BOOL success = NO;
__block NSDictionary *jsonDic = nil;
NSURLSession *session = [NSURLSession sharedSession];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = #"POST"; // 请求方法
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:#13577766655 forKey:#"phoneNumber"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
request.HTTPBody = jsonData; // 请求体
NSCondition *condition = [[NSCondition alloc] init];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Child Thread:%#",[NSThread currentThread]);
if (!error) {
jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
success = YES;
} else {
NSLog(#"%#",error);
}
[condition lock];
[condition signal];
[condition unlock];
}];
[task resume];
// 启动任务
NSLog(#"Main Thread:%#",[NSThread currentThread]);
[condition lock];
[condition wait];
[condition unlock];
NSLog(#"测试时机");
NSLog(#"josnDic:%#",jsonDic);}

Objective-C issues with dataTaskWithRequest

I have recently switched from sendSynchronousRequest to dataTaskWithRequest
with sendSynchronousRequest my method was working perfectly but when I switch to dataTaskWithRequest I get the following error:
error NSURLError * domain: #"NSURLErrorDomain" - code: 4294966096 0x15ee96c0
and
myError NSError * domain: nil - code: 1684370017 0x26cce125
I don't understand why.
Here is the old code (commented out) and the new code:
/*-(NSDictionary *)GetProductionScheduleData:(NSString *)areaDescription
{
NSString *areaDescriptionWSpaceCharacters = [areaDescription stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *requestString = [NSString stringWithFormat:#"%#?areaDescription=%#",kIP,areaDescriptionWSpaceCharacters];
NSURL *JSONURL = [NSURL URLWithString:requestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSDictionary *productionSchedule = [[NSDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return productionSchedule;
}*/
-(void)GetProductionScheduleData:(NSString *)areaDescription Completetion:(void (^) (NSMutableDictionary * result,NSError * error))completion{
NSString *areaDescriptionWSpaceCharacters = [areaDescription stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *requestString = [NSString stringWithFormat:#"%#?areaDescription=%#",kIP,areaDescriptionWSpaceCharacters];
NSURL *JSONURL = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *myError;
NSMutableDictionary *productionSchedule = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(productionSchedule,myError);
}];
[dataTask resume];
}
Please Help! This was working with sendSynchronousRequest I am starting to dislike dataTaskWithRequest.
The NSURLSession code you have is correct, I confirmed with a valid URL.
You stopped checking to see if data is nil before attempting to JSON parse it. If you add that check back I bet you'll find that there is an error and data is in fact nil.
Change to:
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle request error
if (error) {
completion(nil, error);
return;
}
NSError *myError;
NSMutableDictionary *productionSchedule = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(productionSchedule,myError);
}];
I would recommend also checking myError before attempting to set it to productionSchedule (which could also cause a crash).

Resources