【问题标题】:Getting error while converting Json data to Object in iOS在 iOS 中将 Json 数据转换为 Object 时出错
【发布时间】:2016-12-07 17:24:26
【问题描述】:

我正在使用 API 将 Json 数据转换为对象数据, 请访问我正在使用的 API Please Visit the API page which I am using

这是我的代码的快照,其中突出显示了问题 Issues

这是原始代码

 -(void) retrieveData{
    NSURL * url = [NSURLURLWithString:getDataUrl];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];

NSLog(@"JsonArray %@", jsonArray);

//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];

//Loop through our jsonArray

for (int i = 0; i<jsonArray.count; i++)
{
    NSString * yId = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"id"];
   // NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:@"id"];
    NSString * yName = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"name"];
    NSString * yDescription = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"description"];
    NSString * yImage = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"image"];

    //Add the city object to our citiesArray

    [yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];

     }
[self.tableView reloadData];

     }

【问题讨论】:

  • objectAtIndex:@"categories" => 为什么要放一个 NSString 呢?此外,在尝试解析 JSON 之前,您需要了解它的结构。
  • 你能打印NSLog(@"JsonArray %@", jsonArray);]
  • 你能像这样访问数组吗
  • 你能找到一个不到五年的教程吗?没有理由不使用[] 索引。
  • 那我现在该怎么办?我浏览了 API,在那里我使用了 objectAtIndex:@"something" where is" [ " used。并使用 ObjectForKey:@"something" where "{ " used.

标签: ios objective-c json nsmutablearray nsmutablestring


【解决方案1】:

感谢@Lame,我遵循了您的代码,因为它给了我 6 到 8 个错误,但我理解您的代码和配置错误,因为现在这里是根据我的要求工作的完整解决方案或(根据我问的问题)

-(void) retrieveData{
    NSURL * url = [NSURL URLWithString:getDataUrl];
    NSData * data = [NSData dataWithContentsOfURL:url];
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    NSDictionary *dataJSON = [jsonDict objectForKey:@"data"];
    NSArray *allCategoriesJSON = [dataJSON objectForKey:@"categories"];

    yougaArray = [[NSMutableArray alloc] init];

    for (int i = 0; i < allCategoriesJSON.count; i ++)
    {
        NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
        NSString *yId = [aCategoryJSON objectForKey:@"id"];
        NSString *yName = [aCategoryJSON objectForKey:@"name"];
        NSString *yDescription = [aCategoryJSON objectForKey:@"description"];
        NSString *yImage = [aCategoryJSON objectForKey:@"image"];
        [yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
    }
    [self.tableView reloadData];

【讨论】:

    【解决方案2】:

    根据您的 JSON 响应,它是 Dictionary 类型对象而不是 array,因此您的代码应该是这样的,

        NSMutableDictionary *dictData = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
    
        NSLog(@"JsonArray %@", dictData);
    
           NSArray *jsonArray=[[dictData objectForKey:@"data"] objectForKey:@"categories"];
        //setup yougaArray
        yougaArray = [[NSMutableArray alloc] init];
    
    
        for (int i = 0; i<jsonArray.count; i++)
        {
    
    
            NSString * yId = [[jsonArray objectAtIndex:i] objectForKey:@"id"];
            // NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:@"id"];
            NSString * yName = [[jsonArray objectAtIndex:i] objectForKey:@"name"];
            NSString * yDescription = [[jsonArray objectAtIndex:i] objectForKey:@"description"];
            NSString * yImage = [[jsonArray objectAtIndex:i] objectForKey:@"image"];
    
            //Add the city object to our citiesArray
    
            [yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
    
        }
        [self.tableView reloadData];
    

    希望它对你有用。让我知道!! 快乐编码。 :)

    【讨论】:

    • 感谢@Ravi 的贡献,我已经上传了所提问题的解决方案,请查看。
    【解决方案3】:

    你的 JSON 看起来像这样:

    {
    "meta": {
        "status": "200",
        "msg": "OK"
    },
    "data": {
        "total_pages": 0,
        "total_categories": 2,
        "current_page": 1,
        "next_page": 0,
        "categories": [{
            "id": "2",
            "name": "Articles",
            "description": "Yoga Articles",
            "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
        }, {
            "id": "1",
            "name": "Poses",
            "description": "Yoga Poses",
            "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
        }]
    }
    }
    

    现在用下面的代码替换您现有的代码:

    NSData * data = [NSData dataWithContentsOfURL:url];
    jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
    
    NSLog(@"JsonArray %@", jsonArray);
    
    //setup yougaArray
    yougaArray = [[NSMutableArray alloc] init];
    
    //Loop through our jsonArray
    
    NSArray *dataArray = [[jsonArray objectForKey@"data"] objectForKey:@"categories"];
    
    for (int i = 0; i < dataArray.count; i++) {
        NSString * yId = [[dataArray objectAtIndex:i] objectForKey:@"id"];
        NSString * yName = [[dataArray objectAtIndex:i] objectForKey:@"name"];
        NSString * yDescription = [[dataArray objectAtIndex:i] objectForKey:@"description"];
        NSString * yImage = [[dataArray objectAtIndex:i] objectForKey:@"image"];
    
        //Add the city object to our citiesArray
    
        [yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
    }
    
    [self.tableView reloadData];
    

    让我知道解决方案是否适合您,如果出现任何问题。

    【讨论】:

    • 感谢@Siddharth Sunil 的时间、关注和贡献,我已经为所提问题上传了解决方案。这是另一个人“跛脚”给出的,我解决了一些错误。
    【解决方案4】:

    这是 JSON:

    {
        "meta": {
            "status": "200",
            "msg": "OK"
        },
        "data": {
            "total_pages": 0,
            "total_categories": 2,
            "current_page": 1,
            "next_page": 0,
            "categories": [{
                "id": "2",
                "name": "Articles",
                "description": "Yoga Articles",
                "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
            }, {
                "id": "1",
                "name": "Poses",
                "description": "Yoga Poses",
                "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
            }]
        }
    }
    

    您的 JSON 是顶级的 NSDictionary!不是NSArray! 另外,避免在同一行/指令中执行所有objectForKey:/objectAtIndex:,这样会更难阅读,也更难调试,尤其是当您不知道自己在做什么时。 还有,有错误参数的时候,就用吧,不要放nil

    所以:

    NSError *errorJSON = nil;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJSON];
    if (errorJSON)
    {
        NSLog(@"ErrorJSON: %@", errorJSON);
        return;
    }
    NSDictionary *dataJSON = [jsonDict objectForKey:@"data"];
    NSArray *allCategoriesJSON = [dataJSON objectForKey:@"categories"];
    for (NSUIInteger i = 0; i < allCategoriesJSON.count; i ++)
    {
        NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
        NSString yID = [aCategoryJSON objectForKey:@"id"];
        NSString yName = [aCategoryJSON objectForKey:@"name"];
        NSString yDescription = [aCategoryJSON objectForKey:@"description"];
        NSString yImage = [aCategoryJSON objectForKey:@"image"];
        [yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
    }
    

    【讨论】:

    • @Lame 感谢您的帮助,首先我遵循“Monika Patel”的上述代码,这很有帮助,但没有给我适当的解决方案来将数据加载到我需要的对象中我做了一些小的合适的改变,这是无法给出的我是我所需的解决方案,因为我愿意将数据放入我创建的对象中,例如 yId、yName、yDescription、yImage,但是当我使用您的代码时,我配置的错误很少,现在它给了我所需的解决方案。等等,我正在向其答案区域提交解决方案,因此根据我的说法,您建议的代码是正确的解决方案。
    • 我没有用编译器挑战我的代码。我只是在这里写的。可能存在语法上的小问题。有什么错误?
    • 我已经上传了你的代码的更正版本,请检查一下,非常感谢,你的工作真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2020-01-31
    • 2023-03-18
    相关资源
    最近更新 更多