ASIHTTPRequest convert response data to NSArray - iphone

I am using ASIHTTPRequest to get JSON response from server. And I want to convert this response to NSArray. My code:
NSURL *url = [NSURL URLWithString:#"http://chirkov.net.ua/iosnettest/request.php?act=showdata&query=2;0;3;0;ASC"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSData *responseData = [[NSMutableData alloc] initWithData:[request responseData]];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
NSLog(#"array = %#",array);
}
But got exception Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive (0xffffffef, 0xffffffbb, 0xffffffbf, 0x5b, 0x7b, 0x22, 0x69, 0x64.
How can I solve my problem?

You getting JSON data so you have to convert that data using NSJSONSerialization. Have a look at class reference.
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
Also check this Working with JSON

You can use NSJSONSerialization like this:
NSError *jsonError = nil;
NSArray *jsonObject = (NSArray *)[NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];

Related

json return to the format

Api Address:
http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone
return:
KISSY.Suggest.callback({"result": [["iphone4s", "9809"], ["iphone5", "13312"], ["iphone4 手机", "69494400"], ["iphone5 港行", "14267"], ["iphone5三网", "2271160"], ["iphone4手机壳", "6199679"], ["iphone 5手机壳", "2527284"], ["iphone 5 保护壳", "5727586"], ["iphone 4贴膜", "147271"], ["iphone5壳", "2628540"]]})
NSURL * url = [NSURL URLWithString:#"http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSHTTPURLResponse* urlResponse = nil;
NSError * error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSData *date = [NSData alloc]init
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
// NSMutableArray *array=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSMutableArray *array = [jsonParser objectWithData:responseData];
NSLog(#"%#",array);
this array is null. i dont know the reason.
as i refer you request URL ,it has callback in it, if you keep it, it will not return you json as response, so remove "&callback=KISSY.Suggest.callback" from your URL
// Make sure you have include SBJSON files in your Project, as well you have imported header in your View Controller
#import "JSON.h"
// your request URL
NSURL * url = [NSURL URLWithString:#"http://suggest.taobao.com/sug?area=etao&code=utf-8&q=iphone"];
// URL Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSHTTPURLResponse* urlResponse = nil;
NSError * error = nil;
// initiate Request to get Data
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
// Encode your Response
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];
// Now read a Dictionary from it using SBJSON Parser
NSDictionary *responseDict = [content JSONValue];
NSLog(#"Response [%#]",responseDict);
I'm not familiar with the SBJsonParser, but the format of the returned string looks like JSONP, not JSON. I would imagine simply cleaning out the wrapper call would get you what you are after.
Also, note that the 'root' of your response is a dictionary, not an array.
{"result": [[...
means that the code might should look like this:
NSDictionary *response = //... decode
NSArray *results = [response objectForKey:#"result"];
Edited
You just need to use http://suggest.taobao.com/sug?area=etao&code=utf-8&q=iphone instead of http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone you own code will work..

'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]: unrecognized selector sent to instance 0x6695330'

While creating a login view on my iphone app, I ran into this error:
'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]:
unrecognized selector sent to instance 0x6695330'
It's coming from this line:
NSDictionary *results = [parser objectWithString:json_string error:nil];
From this method:
+ (BOOL)loginWithUsername:(NSString *)username password:(NSString *)password
{
NSString *urlString = [NSString stringWithFormat:#"%#login3", ROSE_ROOT_URL];
NSURL *url = [NSURL URLWithString:urlString];
NSString *requestString = [NSString stringWithFormat:#"&mobile=1&username=%#&password=%#", username, password];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:[requestString UTF8String] length:[requestString length]]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[request release];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON product objects
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *results = [parser objectWithString:json_string error:nil];
[json_string release];
[parser release];
// NSDictionary *results = [RoseFetcher fetch:request];
// [request release];
if ([[results objectForKey:#"password"] intValue] == 0)
return NO;
return YES;
}
Any help or explanation would be greatly appreciated.
According to the documentation for SBJsonParser, it doesn't have a method called -objectWithString:error: - an opinion that's corroborated by your findings at runtime. Try sending it a message it will respond to, like -objectWithString:.

Wunderground API json lookup on iPhone

Never touched json before. I'm trying to access some variables within the Wunderground weather API for Melbourne. For example, let's say I want to access the "wind_dir":"East" variable. This is my code thus far:
NSString *urlString =
[NSString stringWithFormat:
#"http://api.wunderground.com/api/key/geolookup/conditions/forecast/q/-33.957550,151.230850.json"];
NSLog(#"URL = %#", urlString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *weatherInfo = [parser objectWithString:json_string error:nil];
for (NSDictionary *weatherString in weatherInfo)
{
NSLog(#"some weather info = %#", [[[weatherString objectForKey:#"response"] objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
}
My code reaches the for loop and crashes with this error: -[NSCFString objectForKey:]: unrecognized selector sent to instance.
I'm not 100% sure what's causing the crash, and whether my path to the "wind_dir" variable is correct, though they could well be the same problem.
Thanks in advance for any help.
either the "response" property or the "current_observation" propery is string and not dictionary.
the error you are getting is that you are trying to call "objectForKey" on a string.
after looking at the result of the API, it seems that you are not getting an array.
You should do something like this:
NSDictionary *weatherInfo = [parser objectWithString:json_string error:nil];
NSLog(#"some weather info = %#", [[weatherInfo objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
instead of your for statement.

Encoding Problem in iphone

Below is my code..
NSString *strResponce = [[NSString alloc] initWithData:JsonData encoding:NSASCIIStringEncoding];
here string has some data.
[JsonData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
ArrayWebContent=[json objectWithString:strResponce error:&error];
But array is null.
any suggestion....
check your json data first put the content of the string strResponce in to the url
Checking json data are proper for parsing
if it gonna generate the parse error than you should check the content of the ws as it may content special charactor for which iphone can not support parsing
good luck
Try with below functions.
- (id) objectWithUrl:(NSURL *)url
{
SBJSON *jsonParser = [SBJSON new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
Let me know for any difficulty.

Google Translate API for iPhone - UTF8 problem in Chinese Translation

I've tested a workable translation API url by:
http://translate.google.com/translate_a/t?client=t&text=%E5%BB%A3%E5%A0%B4&langpair=zh|zh-CN
And it returns the correct result as the following which is in JSON format:
{"sentences":[{"trans":"广场","orig":"廣場","translit":"Guǎngchǎng"}],"src":"zh-CN"}
However, when I try to use this function in XCode, I experienced this problem ...
Here is my code:
NSData *data;
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=zh|zh-CN",qText];
NSURL *url = [[NSURL alloc] initWithScheme:#"http"
host:#"translate.google.com"
path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //Problem's here. It returns nil.
NSLog(result);
Initially I guessed it's encoding problem so I tried other encoding as well (NSISOLatin1StringEncoding) , but I got wrong answer: {"sentences":[{"trans":"ã ","orig":"ã ","translit":"Tu¨¯ "}],"src":"zh-CN"}
Does anyone know how to solve this problem? Thank you very much!
Have you tried checking the error object? If an error occurs, this call will just set the error object and continue - it won't crash/throw like a normal error.
Try something like this after the sendSynchronousRequest call:
if (error != nil)
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
This should give more details if an error occurred.