Response is null - ios

My response is shown null. But when you enter the url in your browser it shows 1. But in my code it returns 0.
The url is http://boomagift.ramansingla.com/forgotpassword.php?email=nihal#gmail.com. I would really appreciate it if someone could help me out. I am new to iOS .
+(NSDictionary *)forgotpassword:(NSString *)email
{
NSDictionary *dict=[[NSDictionary alloc]init];
NSString *urlStr=[NSString stringWithFormat:#"http://boomagift.ramansingla.com/forgotpassword.php?email=%#",email];
NSLog(#"%#",urlStr);
NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
dict = [self sendRequest:request];
NSLog(#"%#",dict);
return dict;
}
+(NSDictionary *)sendRequest:(NSMutableURLRequest *)request
{
NSHTTPURLResponse *response;
NSError *error;
NSData *responseData;
responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(responseData&&[responseData length])
{
NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
return dictionary;
}
else
{
UIAlertView *noInternetAlert=[[UIAlertView alloc] initWithTitle:#"Boom A GIft" message:#"Server Error" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[noInternetAlert show];
noInternetAlert=nil;
return nil;
}
}

The response data is no valid JSON, because its top item is a number, not a Collection (list or object).
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray,
NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
You can configure the serializer to accept non-collection objects at top level with the options paramater.
enum {
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
NSJSONReadingAllowFragments = (1UL << 2)
};
typedef NSUInteger NSJSONReadingOptions;
NSJSONReadingAllowFragments
Specifies that the parser should allow
top-level objects that are not an instance of NSArray or NSDictionary.
Available in OS X v10.7 and later.
BTW: returning nil (not NULL) with an error-out parameter is not joking, but a hint, what the problem is. ;-)

Related

Converting NSString to JSON with NSJSONSerialization is not working

I have this function:
- (void)checkLogin:(NSString *)pLogin andPassword:(NSString*) pPassword {
//Create the data object.
NSMutableDictionary *tLoginAndPasword = [NSMutableDictionary dictionaryWithObjectsAndKeys:pLogin,#"Login",pPassword,#"Password", nil];
NSMutableDictionary *tData = [NSMutableDictionary dictionaryWithObjectsAndKeys:[_Util serializeDictionary:tLoginAndPasword],#"Data", nil];
//Call the login method.
NSData *tResponse = [_Util getLogin:tData];
if (tResponse != Nil) {
_oLabelErrorLogin.hidden = YES;
[_Util setUser:pLogin andPassword:pPassword];
NSMutableDictionary *tJSONResponse =[NSJSONSerialization JSONObjectWithData:tResponse options:kNilOptions error:nil];
NSString *tPayload = [tJSONResponse objectForKey:#"Payload"];
if([[tJSONResponse objectForKey:#"StatusCode"] isEqual: #"424"]) {
//Set global values.
NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
_Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
_RowCount = _Payload.count;
} else {
NSLog(#"JSON Wrong String %#",tPayload);
}
} else if([[tJSONResponse objectForKey:#"StatusCode"] isEqual: #"200"]){
_Payload = Nil;
}
} else {
//Set global values.
_Payload = Nil;
_oLabelErrorLogin.hidden = NO;
//Clear login data.
_oLogin.text = #"";
_oPassword.text = #"";
[_Util setUser:#"" andPassword:#""];
}
}
The JSON response looks like this:
{
"Payload": "{\"UserName\":\"Marco Uzcátegui\",\"Clients\":[{\"UserProfileId\":4,\"ProfileName\":\"Platform Administrator\",\"ClientName\":\"Smart Hotel Platform\",\"InSession\":true},{\"UserProfileId\":5,\"ProfileName\":\"Administrator\",\"ClientName\":\"La Moncloa de San Lázaro\",\"InSession\":false},{\"UserProfileId\":6,\"ProfileName\":\"Administrator\",\"ClientName\":\"Jardín Tecina\",\"InSession\":false}]}",
"StatusCode": "424",
"StatusDescription": null
}
As you can see, I have a escaped string inside "Payload" that is a correct JSON, so I want to generate another NSMutableDictionary with that string, so I'm doing this:
NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
_Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
_RowCount = _Payload.count;
} else {
NSLog(#"JSON Wrong String %#",tPayload);
}
So I'm creating an NSData from the NSString and asking if is valid, it always returns false.
I have tried to replace the "\" from the string and is not working.
[tPayload stringByReplacingOccurrencesOfString:#"\\\"" withString:#""]
I have tried to create a NSMutableDictionary with the string, but the result is not a dictionary.
NSMutableDictionary *tPayload = [tJSONResponse objectForKey:#"Payload"];
I'm kind of lost here.
Any help will be appreciated.
Regards.
The issue is this line
[NSJSONSerialization isValidJSONObject:tPayloadData]
From the documentation of isValidJSONObject
Returns a Boolean value that indicates whether a given object can be
converted to JSON data.
given object means an NSArray or NSDictionary but not NSData
Remove that check and implement the error parameter in JSONObjectWithDataoptions:error:
The method NSJSONSerialization.isValidJSONObject: checks if an object (e.g. a NSDictonary or NSArray instance) can be converted to JSON. It doesn't check if a NSData instance can be converted from JSON. For NSData, it will always return false.
So just call NSJSONSerialization.JSONObjectWithData:options: and check the result instead.

Worklight Adapter Call in IOS Native Passing JSON Parameter

When using JSON.parse(parameter-value) in JavaScript, the adapter invocation is working correctly, however when doing similarly in a native iOS app, it is failing with the following error.
Javascript Adapter Call:
var invocationData = {
adapter : 'TEST_ADAP',
procedure : 'PROC1',
parameters : [JSON.parse(A)],
};
Native Call:
json= // some json value will be come
MyConnect *connectListener = [[MyConnect alloc] initWithController:self];
[[WLClient sharedInstance] wlConnectWithDelegate:connectListener];
WLProcedureInvocationData *myInvocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"TEST" procedureName:#"test"];
myInvocationData.parameters = [NSArray arrayWithObjects:json, nil];
for (NSString *str in myInvocationData.parameters) {
NSLog(#"values of account test %#",str);
}
PasswardPage *invokeListener = [[PasswardPage alloc] initWithController:self];
[[WLClient sharedInstance] invokeProcedure:myInvocationData withDelegate:invokeListener];
Your line
myInvocationData.parameters = [NSArray arrayWithObjects:json, nil];
is almost right.
The parameters property should be an NSArray (as you did) but the array must be made of string values - NOT a JSON object.
myInvocationData.parameters = [NSArray arrayWithObjects:#"myValue1", #"myValue2", #"myValue3", nil];
If the data you received is not in this format, you need to first convert it to this format. This is out of the scope of this question.
If you are not sure how to convert your existing format into a valid NSArray, please open a new question (tagged with Objective-C, not worklight).
We can pass JSON as NSString in iOS Native code to invoke adapter
Example
//Created Dictionary
NSMutablec *dict = [[NSMutableDictionary alloc]init];
[dict setObject:#"xyz" forKey:#"Name"];
[dict setObject:#"iOS" forKey:#"Platform"];
//Convert it to JSON Data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:nil
error:&error];
//JSON Data To NSString
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
WLProcedureInvocationData * invocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"XYZAdapter" procedureName:#"FunctionXYZ"];
//Passing jsonString (NSString Created out of JSON Data) as array to set Parameters.
[invocationData setParameters:[NSArray arrayWithObject:jsonString]];
[[WLClient sharedInstance] invokeProcedure:invocationData withDelegate:self];

How assign value to a JSON string?

I get this JSON object from my web service
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
When I try to assign a value, for example, to Username JSON string, I get a semantic error:
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
for (NSDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString ;
I know how get the JSON object with NSJSONSerialization class, but my target is how assign the value #"" to the JSON object.
So how can I assign the value #"" to the Username JSON string?
While you are trying to fetched dictionary from array. it is not mutable dictionary so you need to created NSMutableDictionary while fetching data from Array. following code will help you to change username.
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey#"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
Well your assignment operation is written wrong, it should be indeed like this:
If you need to get value from dictionary
usernameString = [dictionary objectForKey:#"Username"];
If you want to set a value to your dictionary, first of all your dictionary should be NSMutableDictionary
[dictionary setObject:usernameString forKey:#"Username"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if(!error && [obj isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)obj;
Booking *booking = nil;
for (NSMutableDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString;
Yes, is a compiler error
You need to have a mutabledictionary inorder to change the value. Try this
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = #"";
[mutableDictionary setValue:#"" forKey:usernameString];
}
Even the answers are correct, I want to add that you do not have to do this your own. NSJSONSerialization already has a solution for that. Simply pass as options one of these:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
when reading the JSON.

reading a json object from a website in objective c

I need to separate sub person, name, age, home addr, office addr from below given json object retrieved from a website
{ "person" :
[{"subperson":{"home":{"id":"kljljk"},"name":"person3","age":"18","addr":{"home addr":"ksdjr","office addr":"kjshdg"}}}]}
tried nsjsonserialization,sbjson and touchJSON api's. returns a dictionary in which person is the key and everything else is the value(format of json string specified below the code)
my code:
NSURLRequest *urlreq = [NSURLRequest requestWithURL:url];
NSData *response = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
[webviv loadRequest:urlreq];
SBJsonParser *jsonparser = [SBJsonParser new];
NSDictionary *json = [jsonparser objectWithData:response];
NSLog(#"%#\n", json);
for(id key in json)
{
NSLog(#"%#=%#",key,[json objectWithKey: key]);
}
//output is
person = (everythingelse starting with [, can't separate name and other required things)
//using NSJSONSerialization
if ([NSJSONSerialization JSONObjectWithData:response options:0 error:&error])
{
NSLog(#"json");
}
NSData *pTL = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSLog(#"%#",pTL);
//Output is the same
//for(int i=0;i<[pTL count];i++)
//{
//NSLog(#"%d",i);
//}
//even with for loop the output is the same
Tell your backend guys(the person who wrote this web service) to change "[" as "(" and "]" as")". ( is array { is dictionary. [ is nothing for us we can differentiate it
There is a problem with your JSON structure.
For instance, the following is not a legal JSON string:
"subperson":"home":{"id":"kljljk"}
Try replacing it with the following:
{"person":[{"subperson":{"id":"kljljk","name":"person3","age":"18","addr":{"homeaddr":"ksdjr","office addr":"kjshdg"}}}]}
You can use any kind of online JSON parser tool to verify the JSON structure before continuing to debug your code.
Also you should read a little about JSON syntax here.

Count how many of a certain object appear in a JSON query

I'm returning JSON with a rough structure like the one below, and I'm trying to figure out how I can count how many platforms there are (in this case, three, but could be anything from 1 to 20 or so). I've returned the JSON into an NSDictionary and am using lines such as these to retrieve the data I need:
_firstLabel.text = _gameDetailDictionary[#"results"][#"name"];
In the above case, it'll grab the name from the results section. Since there are multiple platforms, I need to construct a loop to cycle through each name inside the platforms section. Not too sure how to go about that. All help appreciated!
"results":{
"platforms":[
{
"api_detail_url":"http://",
"site_detail_url":"http://",
"id":18,
"name":"First Name"
},
{
"api_detail_url":"http://",
"site_detail_url":"http://",
"id":116,
"name":"Second Name"
},
{
"api_detail_url":"http://",
"site_detail_url":"http://",
"id":22,
"name":"Third Name"
}
],
EDIT: Here's my fetchJSON method:
- (NSDictionary *) fetchJSONDetail: (NSString *) detailGBID {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: YES];
NSString *preparedDetailURLString = [NSString stringWithFormat:#"http://whatever/format=json", detailGBID];
NSLog(#"Doing a detailed search for game ID %#", detailGBID);
NSData *jsonData = [NSData dataWithContentsOfURL: [NSURL URLWithString:preparedDetailURLString]];
_resultsOfSearch = [[NSDictionary alloc] init];
if (jsonData) {
_resultsOfSearch = [NSJSONSerialization JSONObjectWithData: jsonData
options: NSJSONReadingMutableContainers
error: nil];
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: NO];
NSString *results = _resultsOfSearch[#"number_of_page_results"];
_numberOfSearchResults = [results intValue];
NSArray *platforms = [_resultsOfSearch valueForKey:#"platforms"];
int platformsCount = [platforms count];
NSLog(#"This game has %d platforms!", platformsCount);
return _resultsOfSearch;
}
The "platforms" JSON field is an array, so assuming you've de-serialised the JSON using something like,
NSMutableDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:resultsData options:NSJSONReadingMutableContainers error:&error];
Then, you can assign platforms to an NSArray,
NSDictionary *results = [responseJSON valueForKey:#"results"];
NSArray *platforms = [results valueForKey:#"platforms"];
...and find the number of platforms via,
int platformsCount = [platforms count];
In your case, where you want to iterate through the platforms, you can use,
for (NSDictionary *platform in platforms)
{
// do something for each platform
}

Resources