解析此 JSON 字符串时遇到问题。解析这个字符的 JSON 字符串和没有开始和结束括号的方法有什么不同吗?
JSON 看起来像这样。
[
{
"id": 66,
"username": "simon"
},
{
"id": 69,
"username": "simon"
},
{
"id": 70,
"username": "simon"
},
{
"id": 71,
"username": "simon"
}
]
我的代码:
-(void)searchUserNamed:(NSString *)userID andAddTo:(UITableView*)tableView andAddUsersTo:(NSMutableArray*)users
{
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
NSNumber *own_id = @([[NSUserDefaults standardUserDefaults] integerForKey:@"id"]);
NSMutableDictionary *HTTPPostDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
userID, @"username",
token, @"token",
own_id, @"user_id",
nil];
[[WebAPI sharedInstance] commandWithParams:HTTPPostDictionary command:@"search_user" onCompletion:^(NSDictionary *json){
for(NSDictionary *username in json){
NSLog(@"username: %@ FOUND", username);
[users addObject:username];
}
[tableView reloadData];
}];
}
**Which utilizes**
-(void)commandWithParams:(NSMutableDictionary*)params command:(NSString *)command onCompletion:(JSONResponseBlock)completionBlock
{
NSString *_path = [NSString stringWithFormat:@"%@%@",self.baseURL, command];
NSLog(@"path: %@", _path );
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
NSNumber *userID = @([[NSUserDefaults standardUserDefaults] integerForKey:@"id"]);
if(userID)[params setObject:userID forKey:@"user_id"];
if(token)[params setObject:token forKey:@"token"];
NSLog(@"%@",params);
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:@"POST"
path:_path
parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//TODO: attach file if needed
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
NSLog(@"%@",responseObject);
if([responseObject objectForKey:@"status"] && ![[responseObject objectForKey:@"status"] isEqualToString:@"ok"] )
;
else {
NSLog(@"%@",responseObject);
completionBlock(responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"ERROR"]);
// Unable to establish a connection to the server.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Server error"
message:@"Please try again later"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}];
[self enqueueHTTPRequestOperation:operation];
}