-3

解析此 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];
    }
4

3 回答 3

1
[
    {
        "id": 66,
        "username": "simon"
    },
    {
        "id": 69,
        "username": "simon"
    },
    {
        "id": 70,
        "username": "simon"
    },
    {
        "id": 71,
        "username": "simon"
    }
]

这个 JSON 和上面不带括号的 JSON 的区别在于,上面的 JSON 是有效的,不带括号的则是无效的 JSON。

于 2013-06-20T10:12:30.313 回答
0

在 ViewController.h

    NSString *idStr;
    NSString * usernameStr;
    NSMutableArray *dataSourceArray;
    NSMutableDictionary *MutableDictionry;

在 ViewController.m 中

-(void) viewDidLoad
{
    dataSourceArray =[NSMutableArray new];
    NSArray *array;//this array will contain your json
    dataSourceArray = [self usersFromArray:array];        
 }
- (NSMutableArray *)usersFromArray:(NSArray *)array
 {
     NSMutableArray *users = [NSMutableArray array];
     for (NSDictionary *dict in array) {
if (dict)
       {
              idStr = dict[@"id"];
              usernameStr = dict[@"username"];
        MutableDictionry=[NSDictionary dictionaryWithObjectsAndKeys:idStr,@"id",usernameStr,@"username",nil];

       }
    [users addObject:MutableDictionry];
 }
return users;
}
于 2013-06-20T10:09:22.533 回答
0
for(NSDictionary *username in json)

json 是NSDictionary,但你的 json 结果是数组,将 json 更改为NSMutableArray

我对你的建议,不使用 for 循环添加对象以使用 addObjectsFromArray:像这样

[user addObjectsFromArray:json];//change json is an array
于 2013-06-20T10:36:36.550 回答