在iOS中,如何将JSON字符串解析为对象

who*_*ows 10 json objective-c ios

我来自Android开发人员,很抱歉,如果我在这里缺少明显的iOS概念.

我有一个JSON提要,看起来像:

{"directory":[{"id":0,"fName":"...","lName":"...","title":"...","dept":"...","bld":"...","room":"...","email":"...","phone":"..."},{"id":1,"fName":"...","lName":"...","title":"...","dept":"...","bld":"...","room":"...","email":"...","phone":"..."}]}

然后,我有一个Staff.h和.m,其中的类具有匹配它的属性(id,fName,lName)等.

我已经在这工作了几个小时,但我似乎无法将JSON字符串解析为一个Staff对象数组.最终目标是让他们进入核心数据,所以任何建议都会很好.

我已阅读的教程没有显示如何使用{"目录"形式的JSON字符串:[{...}]}我在Android应用程序中执行此操作没有问题,但我已经没有了iOS(6)在objective-c中的想法.

谢谢阅读.

Jan*_*mal 18

你可以这样做

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];//response object is your response from server as NSData

if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
    NSArray *yourStaffDictionaryArray = json[@"directory"];
    if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){//Added instrospection as suggested in comment.
        for (NSDictionary *dictionary in yourStaffDictionaryArray) {
            Staff *staff = [[Staff alloc] init];
            staff.id = [[dictionary objectForKey:@"id"] integerValue];
            staff.fname = [dictionary objectForKey:@"fName"];
            staff.lname = [dictionary objectForKey:@"lName"]; 
            //Do this for all property
            [yourArray addObject:staff];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)