应用程序崩溃,因为NSArray objectforkey:Objective C

Bla*_*des 0 parsing json objective-c httprequest

我试图用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
Run Code Online (Sandbox Code Playgroud)

这是我的json:

[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]
Run Code Online (Sandbox Code Playgroud)

我试图从字符串中获取AssestName.我一定做错了什么.

Wai*_*ain 5

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

NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
                                                options:kNilOptions
                                                  error:&error];

NSDictionary* defineJsonData = [json lastObject]; //2

NSLog(@"value: %@", [defineJsonData objectForKey:@"AssetDesc"]); //3
Run Code Online (Sandbox Code Playgroud)