我一直在解析Xcode中的JSON:
-(void)getCheckUserData:(NSData *)data {
NSError *error;
if (!error) {
checkUserJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Uh Oh" message:@"Spaghetti-O" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void) startCheckingUserLogin {
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:kCheck_user]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest
delegate:self];
if (theConnection) {
NSURL *url = [NSURL URLWithString:kCheck_user];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getCheckUserData:data];
}
}
但我聘请了一位网络开发人员,他更新了我过时的php文件,这些文件从phpmyadmin获取数据并用JSON编码。现在我在xcode中收到一条NSCocoaErrorDomain Code = 3840消息。
这是我从以下网址获取数据的php文件:
<?php
require_once( 'classes/secure.php' );
$SECURE = new Secure();
if( !isset( $_POST[ 'var1' ] ) ) { exit("ERROR: no var1"); }
if( !isset( $_POST[ 'var2' ] ) ) { exit("ERROR: no var2"); }
$VARONE = $_POST[ 'var1' ];
$VARTWO = $_POST[ 'var2' ];
$RESULT = $SECURE->checkPassword( $VARONE, $VARTWO ); // Check VARONE / VARTWO
unset( $SECURE ); // Unset Secure
exit( json_encode( $RESULT ) ); // Return result as JSON string
?>
我需要改变什么?
答案 0 :(得分:3)
问题在于编码。我有一个网络服务99%的时间工作正常,但一个端点的某个参数响应失败。我在RESTClient中运行了请求,并在标题中注意到响应是ISO-8859-1,也就是拉丁语-1。
诀窍是将Latin-1数据转换为NSString,然后使用NSString转换回UTF8数据以使NSJSONSerialization满意。
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:self->receivedData options:0 error:&error];
if (!json && error && [error.domain isEqualToString:NSCocoaErrorDomain] && (error.code == NSPropertyListReadCorruptError)) {
// Encoding issue, try Latin-1
NSString *jsonString = [[NSString alloc] initWithData:self->receivedData encoding:NSISOLatin1StringEncoding];
if (jsonString) {
// Need to re-encode as UTF8 to parse, thanks Apple
json = [NSJSONSerialization JSONObjectWithData:
[jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]
options:0 error:&error];
}
}
我确信那里有很多很棒的REST工具,你可能想要查看其中的一些。 RESTClient是Firefox的插件。