【问题标题】:App crashing because NSArray objectforkey: Objective C应用程序崩溃,因为 NSArray objectforkey: Objective C
【发布时间】:2013-05-22 12:18:01
【问题描述】:

我正在尝试使用 Objective C 解析一些 Json。

我的问题是我得到了正确的 json,但是当我尝试解析一些 json 时,我的应用程序崩溃了。

// i will use a code from connect to DB tutorial
NSString *strURL = [NSString stringWithFormat:@"http://www.ddproam.co.za/Central/Asset/AssetsWithSerial?Serial=S00000001"];

// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];

NSLog(@"Login response:%@",strResult);

NSError *error;
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
                                                     options:kNilOptions
                                                       error:&error];

NSArray* defineJsonData = [json objectForKey:@"AssetDesc"]; //2

NSLog(@"value: %@", defineJsonData); //3

这是我的 json:

[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]

我正在尝试从字符串中取出 AssestName。我一定是做错了什么。

【问题讨论】:

    标签: objective-c json parsing httprequest


    【解决方案1】:

    整个事情是一个包含字典的数组,而不是包含数组的字典...... 这是一种非常肮脏的方式来获得你想要的价值——你想写一些比这更安全的东西。在尝试使用它之前尝试检查返回的类的类型...

    NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
                                                    options:kNilOptions
                                                      error:&error];
    
    NSDictionary* defineJsonData = [json lastObject]; //2
    
    NSLog(@"value: %@", [defineJsonData objectForKey:@"AssetDesc"]); //3
    

    【讨论】:

    • 非常感谢@Wain 为我解决这个问题。很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多