我在我的应用程序中使用AFNetworking框架,我能够发出HTTP请求并能够从服务器获得响应,但我无法解析JSON。
以下是我的代码:
我创建了一个名为WebServices的单例类,并创建了一个发出HTTP请求的方法。
+(void)getCompaniesc:(NSString *)companyID onSucess:(PSACompletionBlock2)onSucess
{
NSDictionary *params = @{@"companyId": companyID};
[[[WebServices sharedInstance] operationQueue] cancelAllOperations];
[[WebServices sharedInstance] postPath:@"GetCompany?" parameters:params success:^(AFHTTPRequestOperation *operation, id response)
{
NSString *st = [NSString stringWithFormat:@"%@",response];
NSLog(@"st=%@",st);
if (onSucess)
{
onSucess(YES, response);
}
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error);
}];
}
并从我的ViewController
我使用以下代码调用上述函数:
[WebServicesClass getCompaniesc:companyID onSucess:^(BOOL success, id jsonresponse) {
}];
我从服务器获得类型为id
的响应。
以下是我对服务器的回复:
[{"ExistsInDB":"False","CanSave":"True","EntityName":"ACCOUNT","TypeDescription":"Company","TypePluralDescription":"Companies","RequiredProperties":"Chiever.Data.SAQueryFieldSet","MetaData":"","ReadOnly":"False","ACCTNAME":"","AREA_ID": "","ACCT_TYPE_ID":"","ADDR1":"","ADDR2":"","ADDR3":"","TOWN”:””,”COUNTY":"","POSTCODE":"","COUNTRY":"","TEL":"","FAX":"","EMAILORWEB":"","BUYGRP_ID": "","STATUS":"","SIC_CODE_ID”:””,”CURRENCY_ID":"","CALL_FREQ": "0","DORMANT":"False","CREATOR_ID": "","CREATED_ON":"01/01/0001 00:00:00","LAST_EDITOR_ID":"","LAST_EDITED":"01/01/0001 00:00:00","LAST_ACTION_BY":"","LAST_ACTION":"01/01/0001 00:00:00","NEXT_ACTION_BY":"","NEXT_ACTION":"01/01/0001 00:00:00","LOCALE_ID":"","BusinessUnits": "System.Collections.Generic.List`1[chiever.Platform.LookupIdValuePair]","ACCT_ID":"0000000320"}]
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
做这个检查:
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData: jsonresponse options:NSJSONReadingMutableContainers error:&error];
如果您的返回是一个数组,请使用:
NSArray *arr = [NSJSONSerialization JSONObjectWithData: jsonresponse options:NSJSONReadingMutableContainers error:&error];
答案 1 :(得分:1)
A。)如果您使用AFHTTPRequestOperation
,请确保设置responseSerializer
:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
operation.responseSerializer = [AFJSONParserResponseSerializer serializer];
另外,请确保将“Content-Type”请求设置为“text / json”。现在,如果您从服务器获得JSON响应,那么您可能应该获得字典responseObject
。
B。)如果您仍然获得NSData
,则可以将NSData
转换为NSString
以查看/调试您从服务器获取的内容:
NSString *stringResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // Use appropriate encoding
NSLog(@"String Response: %@", stringResponse);
C。)如果你确定从服务器获得了json响应,你总是可以使用json序列化将原始NSData
响应转换为NSDictionary
:
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"JSON: %@", json);
希望这有帮助。
答案 2 :(得分:0)
如果您的服务器返回"Content-Type: application/json"
标头,您将获得一个NSDictionary
来自AFNetworking的json响应。或者在您的情况下,包含NSDictionaries的NSArray
。
在PHP中,可以通过添加
来修改标题header('Content-Type: application/json');
到脚本的顶部。