我有 2 个问题:我需要从下面的 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
}
提前感谢您的帮助。