[英]iOS 7 NSJSONSerialization
我正在嘗試開發一個解析json數據的應用程序。 我有以下json:
{
myobject:[
{
id:184,
title: "test title"
}
]
}
我有以下代碼,我正在嘗試從此json獲取標題數據
NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSError *error = nil;
NSDictionary *currentObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(error)
{
NSLog(@"%@",error);
}
NSDictionary *nar = [currentObject objectForKey:@"myobject"];
NSLog(@"%@",[nar valueForKey:@"title"]);
NSString *curTitle = [nar valueForKey:@"title"];
self.myTitle.text = curTitle;
登錄標題時,可以看到標題確實又回來了。 但是,當我嘗試設置myTitle.text時,出現以下錯誤
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x15631850
在您的json中,我的object字段不是字典,而是字典數組,因此[nar valueForKey:@"title"]
將為該數組中的每個元素返回valueForKey數組。
如果您不確定數據格式,則可以通過以下方式從中提取字符串值:
NSArray *nar = [currentObject objectForKey:@"myobject"];
NSString *curTitle = nar[0][@"title"];
但是,當然最好在生產代碼中添加一些數據驗證/錯誤處理。
崩潰是因為您的字典包含NSArray
而不是字典。
NSArray *ar = [currentObject objectForKey:@"myobject"];
for(NSDictionary *dict in ar)
{
NSLog(@"%@", [dict objectForKey:@"title"];
)
}
NSString *curTitle = [[ar objectAtIndex:0] objectForKey:@"title"];
self.myTitle.text = curTitle;
您正在嘗試將NSArray
分配給self.myTitle.text
。
NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSError *error = nil;
NSDictionary *currentObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(error)
{
NSLog(@"%@",error);
}
NSArray *nar = [currentObject objectForKey:@"myobject"];
NSString *title = [[nar objectAtIndex:0] objectForKey:@"title"];
NSLog(@"%@",title);
self.myTitle.text = title;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.