【发布时间】:2013-02-08 17:20:42
【问题描述】:
我有两个问题: 我需要从下面的 JSON 中获取“元素”和“类别”到我的核心数据持久存储/数据库中,我尝试了以下(下面的代码),但我对我是否做对了感到困惑和困惑怎么办?
当我尝试使用嵌套的 objectForKey 获取元素数组时,我也遇到了错误,为什么以及如何解决它?
错误,我不明白,因为 Elements 是一个数组?
reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1cd2f4a0'
我收到带有 AFNetworking 的 JSON,如下所示:
[[MyAPIClient sharedClient] getPath:domain parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
//IS THIS THE RIGHT WAY TO PROCESS NESTED JSON DATA IN CORE DATA?
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:JSON options:0 error:&error];
NSArray *arrayOfCategoriDictionaries = (NSArray *)[[jsonDict objectForKey:@"Manifacture"] objectForKey:@"Categori"];
//Categori array to Core data
for( NSDictionary *d in arrayOfCategoriDictionaries) {
Categori *cat = [NSEntityDescription insertNewObjectForEntityForName:@"Categori" inManagedObjectContext:_managedObjectContext];
}
//Elements to core data, get an error with objectForKey:@"Elements" ?
NSArray *arrayOfElementsDictionaries = [[[jsonDict objectForKey:@"Manifacture"] objectForKey:@"Categori"] objectForKey:@"Elements"];
for(NSDictionary *d1 in arrayOfRetDictionaries) {
Elements *elements = [NSEntityDescription insertNewObjectForEntityForName:@"Elements" inManagedObjectContext:_managedObjectContext];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (![_managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}];
嵌套的json数据:
{
"Manifacture": {
"Categori": [
{
"Elements": [
{
"Id": 1,
"Name": "Door",
"Description": "Black door with window",
"Price": 149,
"CategoriId": 1
}
],
"Id": 1,
"Name": "Forret",
"ElementsId": 1,
"Manifacture_Id": 1
}
],
"CarSet": [],
"Id": 1,
"Name": "Hummer",
"Description": "A big car"
},
"Id": 2,
"Name": "Hummer Car Factory",
"Contactperson": "Adil Bujas",
"Location": "California",
"Info": "Hummer LTD",
"SearchThumbnail": "none",
"CarPicture": "none",
"Doors": 5,
"webpages_MembershipUserId": 4,
"Manifacture_Id": 1
}
提前感谢您的帮助。
【问题讨论】:
-
请解释投票否决?
-
这个问题会被反复问多少次?为什么人们不去看看他们该死的 JSON 的结构和/或谷歌错误消息?
-
我有,但由于我是初学者,我对这门语言以及它与我的 JSON 的关系还没有全面的了解,我只是想问问有这方面知识的人。而且由于之前已经被问过很多次,它似乎真的很相关。如果您不喜欢它或不分享您的知识,请忽略这个问题,而不是写这样的评论。
标签: iphone objective-c json core-data