【问题标题】:parsing JSON values from JSON Array in iOS在 iOS 中从 JSON 数组解析 JSON 值
【发布时间】:2014-07-17 11:21:32
【问题描述】:

我正在从服务器获取 JSON 数组形式的响应,如下所示:

{
    "status": "success",
    "data": [
        {
            "auth_Secret_ticket_refresh": "NULL",
            "userId": "10632",
            "loginEmail": "Raushan@gmail.com",
            "auth_authorizationCode": "4cb8c5e8a7f5",
            "accountType": "flickr",
            "auth_Token": "23104658-d2e65d5f94554652",
            "userName": "betterlabpune",
            "auth_subdomain": "NULL"
        },
        {
            "auth_Secret_ticket_refresh": "NULL",
            "userId": "19629",
            "loginEmail": "Ipad@gmail.com",
            "auth_authorizationCode": "8b909cb3e0e1",
            "accountType": "flickr",
            "auth_Token": "77645323118718-bac668bc2b95ad89",
            "userName": "betterlabpune",
            "auth_subdomain": "NULL"
        }
    ]
}

我想从 JSON 数组中提取 0 索引的值、“userId”和“userName”的值。 我曾尝试以多种方式提取值,以下是我的代码:

 NSMutableData * _responseData = [[NSMutableData alloc]init];
    [_responseData appendData:data];
    NSJSONSerialization *dataAsString=(NSJSONSerialization*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    // dataJson=(NSDictionary*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"data in register reponse : %@",dataAsString);
    NSJSONSerialization *json;
    NSDictionary *dataJson;
    NSError *error;

    NSDictionary *JSONE = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
    NSLog(@"JSONE : %@",JSONE);


    json=[NSJSONSerialization JSONObjectWithData:_responseData
                                         options:NSJSONReadingMutableLeaves
                                           error:&error];

      [self processData:dataJson];
   dataJson=[[NSDictionary alloc]init];
   dataJson=(NSDictionary *)json;
    NSString * status=[dataJson objectForKey:@"status"];
  NSString * message=[[dataJson objectForKey:@"data"]objectForKey:@"id"];

    NSLog(@"status : %@",status);
   NSLog(@"message: %@",message);

    NSMutableArray *argsArray = [[NSMutableArray alloc] init];
    argsArray= [dataJson valueForKeyPath:@"status"];
    NSLog(@" client Id : %@", [argsArray objectAtIndex:0]);

每次我的结果都为空时打赌。 请帮帮我。 感谢您宝贵的时间。

【问题讨论】:

  • 首先检查状态是否等于成功然后继续下一步
  • 你在哪里收到空值?在状态和消息日志中?您忘记了 data 是一个数组。要获取 id,您应该这样做: dataJson[@"data"][0][@"id];

标签: ios iphone json


【解决方案1】:

试试这个...

if ([[dataJson  valueForKey:@"status"]isEqualToString:@"success"])
    {
        NSMutableArray *tempArray=[NSMutableArray array];
        for (NSDictionary *tempDic in [dataJson valueForKey:@"data"])
        {

            [tempArray addObject:[tempDic valueForKey:@"userId"]];
        }
        NSLog(@"%@",tempArray);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2018-03-19
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多