【发布时间】:2013-06-20 10:03:06
【问题描述】:
我在解析这个 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];
}
【问题讨论】:
-
提供您尝试过的代码。
-
这是一个字典数组,而不是 JSON Repsonse。向我们展示解析代码。
-
这看起来像一个字典数组的日志。这不是真正的 JSON。
-
也不是日志,用分号的
-
带和不带“那些括号”的 JSON 完全没有区别,因为两者同样无效。
标签: iphone ios objective-c json cocoa-touch