parsing json response in my objective-c program - iphone

im using SBJSON to parse my response, bus somehow i cant get my data out.
how should i parse this reponed ?
{"StatusCode":0,"Message":"email already exists","Content":{"HasApplication":false,"IsFaceBook":false,"UserActive":false,"UserAuthenticationType":0,"UserCredits":0,"UserDayAdded":0,"UserEmail":null,"UserEmailWasVerified":false,"UserGuid":null,"UserID":0,"UserSellerApproved":false,"UserTokef":0},"TotalCount":0}
i start like this :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
NSLog(#"%#",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
NSLog(#"Data recived");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"conenction loading finished");
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil];
}
but whats next ?i need the StatusCode value and the UserID.

One you have the dictionary, you can use it, for example:
NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil];
NSNumber * statusCode = [jsonDictionary objectForKey:#"StatusCode"];
NSString * message = [jsonDictionary objectForKey:#"Message"];
NSDictionary * content = [jsonDictionary objectForKey:#"Content"];
// etc...

From the looks of the JSON string, you have a Dictionary with three Key Value pairs, one of those being another Dictionary with several Key Value pairs. So to deal with that once you have assigned the JSON responseString to your NSMutableDictionary:
Should be something like:
NSNumber *statusCode = [jsonDictionary objectForKey:#"StatusCode"];
NSDictionary *contentDict = [jsonDictionary objectForKey#"Content"];
NSString *userID = [contentDict valueForKey#"UserID"];
On a completely different note, if you are going to be doing a lot of web-service interaction, you may want to take a serious look at AFNetworking. It will change your life :)
Also, I can't see why you would need jsonDictionary to be an NSMutableDictionary. Unless you are changing it later on, use NSDictionary, it has less overhead.

well.....
NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString
Maybe it's not NSMutableDictionary, but NSDictionary.
and then:
NSString *statusCode = [jsonDictionary valueForKey:#"StatusCode"];
NSDictionary *contentDict = [jsonDictionary objectForKey#"Content"];
NSString *userID = [contentDict valueForKey#"UserID"];

Related

How to pass a json object as a parameter to the webservice?

I am using a webservice which takes json object as parameter. Here's my code:
-(void)createHttpHeaderRequest {
NSString *x = #"{\"GetVehicleInventory\": {\"ApplicationArea\": {\"Sender\": {\"ComponentID\":}}}" (something like that)
NSString *sample = [NSString stringWithFormat:#"https://trialservice.checkitout?XML_INPUT=%#",x];
NSString * final = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)sampleReq, NULL, CFSTR(":/?#[]#!$&'()*+,;=\""), kCFStringEncodingUTF8);
NSMutableRequest *request = [NSMutableREquest requestWithURL:[NSURL URLWithString:final]];
NSURLConnection * theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
if (theConnection) {
NSLog(#"Service hit");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSError * error;
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSArray * categories = [dict objectForKey:#"category"];
[self.delegate giveControlBackToController:categories];
}
When I am trying to NSLog sample it gives me the complete URL which on pasting into a browser gives me the result back, but when I am calling NSLog on the request, it shows null and nothing happens after this.
The control never goes to its NSURLConnection delegate method.
The trick is that most browsers automatically escape URLs whilst NSURL doesn't. You'll need to do it manually; have a look at the CFURLCreateStringByAddingPercentEscapes function.
This should probably be a comment instead of an answer, but unfortunately you can't format code in a comment. Add the following method to your delegate and see whether it gets called. If it does, let us know what the response is.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"Connection response code: %d", httpResponse.statusCode);
}

Generating a URL string for NSURLRequest fails to initiate

This one has me pretty confused. If I put in the following:
NSString *LoginURLString = [NSString stringWithFormat:#"http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=13242134"];
//NSLog output: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
And use this in a URL request, it works fine, but I need to make this dynamic, so I have it concatenate the URL string with a new UserID by using the following:
NSString *user = [NSString stringWithFormat:#"%#", [[NSUserDefaults standardUserDefaults]stringForKey:#"CustomerID"]];
//user = [[NSUserDefaults standardUserDefaults] stringForKey:#"CustomerID"];
NSString *LoginURLString = [NSString stringWithFormat:#"http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=%#", user];
//NSLog output: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
Here is the rest of my request initializer:
NSString *urlString = LoginURLString;
responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
And the other methods that handle the request:
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[responseData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[responseData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
// [connection release];
CommonPickUpArray = [[NSMutableArray alloc] init];
CommonLocationInfoArray = [[NSMutableArray alloc] init];
NSString *data = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"%#", data);
}
This request never even starts. I really don't understand why. I have tried to output the two strings to the NSLog and either way they look exactly the same. Can anyone explain? Thanks for your help!
Edit: The Connection didFailWithError method is outputting this:
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xf6a6f50 {NSUnderlyingError=0xf6a75d0 "bad URL", NSLocalizedDescription=bad URL}
Output from answer 1:
2012-05-08 13:45:24.959 AmericanTaxi[1295:707] Connection failed with error: bad URL
2012-05-08 13:45:24.960 AmericanTaxi[1295:707] for the URL: (null)
Output of urlString and LoginURLString:
2012-05-08 13:57:40.415 AmericanTaxi[1320:707] LoginURLString: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
2012-05-08 13:57:40.417 AmericanTaxi[1320:707] urlstring: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
In your didFailWithError, check the URL and see why it is bad by adding this to your didFailWithError delegate:
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
NSLog(#"for the URL: %#", [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
Post the result.

NSURLConnection returns data but I cannot read it

This is another simple question who'se answer escapes me after a hour on Google...
A user is typing something into a text field and upon this field loosing focus, I launch an NSURLConnection....
NSString *usernameTry = [sender text];
NSLog(#"username field = %#",usernameTry);
NSString *content = [#"http://www.siebenware.de/Rhythm/user/checkusername.php?username=" stringByAppendingString:usernameTry];
content = [content stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:content] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
NSLog(#"%#",content);
Then I wait for the response....
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Received Response");
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int status = [httpResponse statusCode];
if (!((status >= 200) && (status < 300))) {
NSLog(#"Connection failed with status %#", status);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[resultsData appendData:data];
NSString *resultsString = [[NSString alloc] initWithData:resultsData encoding:NSUTF8StringEncoding];
NSLog(#"received data %# %i",resultsString,[resultsString length]);
if ([resultsString isEqualToString: #"FAIL"]){
NSLog(#"failed to retrieve data");
}else{
resultsObjects = [[resultsString componentsSeparatedByString:#":"] mutableCopy];
if([resultsObjects objectAtIndex:0]==#"usernamecheck"){
if ([resultsObjects objectAtIndex:1]==username.text) {
if ([resultsObjects objectAtIndex:2]==#"NG"){
//set the check marker to bad
[usernameVer setImage:[UIImage imageNamed:#"redcross.png"]];
}else{
//set the check market to good
[usernameVer setImage:[UIImage imageNamed:#"greentick.png"]];
}
}
}
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Unable to retrieve data" message:[NSString stringWithFormat:#"Error code %i",[error code]] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
I see the response arrive in didReceiveResponse and am getting 18 bytes of data (which is correct).
However didReceiveData says that the 'data' is null. I know I am missing something exceptionally simple, and I promise to kick myself once this is cleared up.
Regards
Chris H
if you want to change the data into an NSString you can do this:
NSString *responsestring = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responsestring);
You need work with your data in:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
Because
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
can be called many times
You can do that:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[myData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// TODO: work with data
}
NSMutableData* myData must be instance var.
You need to convert the NSMutableData received by the NSURLConnection delegate method to readable NSString by using the below code
NSString *finalString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
and that should do it.
Try with other encoding..May be ASCII encoding instead of UTF-8..It may work out

how to give componentsSeparatedByString on regular expression in iphone

Hello friends,
I am doing regulation here i create all and i store in array and print that in console also but i give in group also but when i give componentsSeparatedByString is not working why where i am wrong when i doing this code my application goin crash and log message print this meassage:-
[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x4e283a0
2011-09-12 14:05:48.400 RegexKitLiteDemo[10576:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x4e283a0
This is my code please some one help me in right direction
-(void)sendRequest
{
// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.bookryanair.com/SkySales/FRSearch.aspx"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
// inform the user that the download could not be made
}
}
/// this for checking is that Sync is work or not
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
[connection release];
NSString *regexString = #"Stations\\[""(.*)""\\] = new Station\\((.*)new Array\\((.*)\\)\\);";
matchArray = [loginStatus arrayOfCaptureComponentsMatchedByRegex:regexString];
NSLog(#"matchArray: %#", matchArray);
group = [[NSMutableArray alloc] initWithCapacity:[matchArray count]];
for (int i = 0; i < [matchArray count]; i++) {
NSString *temp = [[matchArray objectAtIndex: i] componentsSeparatedByString: #","];
[group addObject: temp];
NSLog(#"group: %#", group);
}
}
The componentsSeparatedByString method is applied on a NSString and it returns and NSArray;
- (NSArray *)componentsSeparatedByString:(NSString *)separator
e.g. NSArray *array = [aString componentsSeparatedByString:#","];
So, in your code, for starters, the following line is wrong;
NSString *temp = [[matchArray objectAtIndex: i] componentsSeparatedByString: #","];
If you are trying to turn an NSArray of NSString objects into a single string separated by a comma, try it this way:
NSString *temp = [[matchArray objectAtIndex:i] componentsJoinedByString:#","];
componentsJoinedByString called on an array will return a single string from the array components.
componentsSeparatedByString called on a string will return an array made up of the string components (depending on the separator)
Also the error u are receiving is encountered when the instance you are calling the method componentsSeparatedByString is invalid. Here since you are already printing MAtcharray using NSLog, i suggest you check if it is properly printed. Also since you are trying to access element by element and call the components.... method on that do check by printing element by element to confirm if it actually exists.

how to parse the json responseString from webservice

I am connecting to webservices using json.
I connected using nsurl connection. I got json response string ... i need to parse it.
When i try to parse it i am getting following error:
dyld: Symbol not found: _CFXMLNodeGetInfoPtr
here is relevant source code:
// Using NSURLConnection
- (void)viewDidLoad
{
[super viewDidLoad];
dataWebService = [[NSMutableData data] retain];
NSMutableURLRequest *request = [[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.googleapis.com/customsearch/v1?key=AIzaSyDzl0Ozijg2C47iYfKgBWWkAbZE_wCJ-2U&cx=017576662512468239146:omuauf_lfve&q=lectures&callback=handleResponse"]]retain];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
[myConnection start];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[dataWebService setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[dataWebService appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#",responseString);
[responseString release];
[dataWebService release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error during connection: %#", [error description]);
}
// Parse JSON
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSDictionary *dictionary = [responseString JSONValue];
NSDictionary *dictionaryReturn = (NSDictionary*) [dictionary objectForKey:#"request"];
NSString *total = (NSString*) [dictionaryReturn objectForKey:#"totalResults"];
NSLog(#"totalResults: %#", total);
int count = [[dictionaryReturn objectForKey:#"count"] intValue];
NSLog(#"count: %d", count);
}
The JSON response string is not a valid one, that's the reason your are getting the error.
Use the following link to check the if the JSON string, sent as response from Web services is valid one or not
JSONLint