【发布时间】:2016-06-23 09:25:17
【问题描述】:
在我的项目中,我通过这个 API:http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat 和参数:prod_id=25,var_id=140。
问题是当我在 Rest Client 中传递这个 api 时,它会显示正确的响应,但是当我尝试将它放入我的代码中时,它会显示不同的响应。
我正在使用以下代码:
-(void)listofNotice
{
NSString *post = [NSString stringWithFormat:@"prod_id=25,var_id=140"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(@"str : %@",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(@"str : %@",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = @"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
它显示以下响应:
str : {
business = 0;
"business-list" = "Business list empty.";
response = 401;
}
但实际的反应是这样的
请帮帮我..提前谢谢
【问题讨论】:
-
您是否在调用 API 之前进行了一些身份验证,因为它会给出 401 作为响应。虽然这不是正确的方法
-
@abhi : 应该是后端反序列化的问题。使用 AFNetwokring 并在其中使用 AFJSONRequestSerializer 将数据作为参数传递。当您在后端以正常方式发送时,它们可能会得到空值。 AFJSONRequestSerializer 帮助您以正确的 json 格式发送参数。
-
它现在可以工作了我在代码中犯的唯一错误是我使用的是 ,而不是 &
标签: ios objective-c json parsing