从我的后端API,我得到一个由数组,字典,数字,bool,字符串等组成的json对象。例如。
{
data:[
{
id : 1,
name : "abcd"
},
{
id : 2,
name : "abcde"
},
{
id : 3,
name : "abcde"
},
]
total_count : 10
}
有时,total_count中的值是一个数字,有时它是一个字符串。在我的代码中,我编码了
[lbl setText:[jsonObject valueForKey:@"total_count"]]
这会崩溃,因为total_count键值是一个数字。显然我可以做到这一点
[lbl setText:[NSString stringWithFormat:@"%d",[[jsonObject valueForKey:@"total_count"] intValue]]];
但这种情况发生在API的很多地方。字符串来了而不是bool。
data:false
代替data:[]
[编辑]
[[AFHTTPRequestOperationManager manager] GET:[URLString attachToken] parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
if([[[responseObject valueForKey:@"response"] valueForKey:@"status"] boolValue]) {
NSLog(@"success");
}
if(success)success(operation, **responseObject**);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
if(failure)failure(operation, error);
if(operation.response.statusCode == 0) {
ATAFNetworkingRequestObject *obj = [[ATAFNetworkingRequestObject alloc] init];
obj.urlString = URLString;
obj.paramters = parameters;
obj.successBlock = success;
obj.failureBlock = failure;
obj.type = ATNetworkingRequestGET;
if(![self duplicateRequestExists:obj])[pendingAPICalls addObject:obj];
}
[self logAPIFailedWithOperation:operation parameters:parameters error:error];
} autoRetry:5 retryInterval:7];
答案 0 :(得分:1)
根据您的A string is coming instead of a bool. data:false instead of data:[]
if([datajsonObject isKindOfClass:[NSArray class]]){
//Is array
}else if([datajsonObject isKindOfClass:[NSDictionary class]]){
//is dictionary
}else if([datajsonObject isKindOfClass:[NSString class]])
{
//is String
}
else{
//is something else
}
答案 1 :(得分:0)
您可以检查服务器值是否为数字或字符串
NSString *newString = [NSString stringWithFormat:@"%@",[[jsonObject valueForKey:@"total_count"]
if ([newString isKindOfClass:[NSNumber class]])
{
NSLog(@"It is number");
}
if ([newString isKindOfClass:[NSString class]])
{
NSLog(@"It is string");
}
答案 2 :(得分:0)
Swift代码:
lblCount.text = String(datajsonObject["total_count"] as AnyObject)
目标c:
NSString *strCount = [NSString stringWithFormat:@"%@",[jsonObject valueForKey:@"total_count"]]
if ([strCount isKindOfClass:[NSString class]])
{
// Write your code to show on label
}