在iOS中,如何将JSON字符串解析为对象
我来自Android开发人员,很抱歉,如果我在这里缺少明显的iOS概念。
I come from Android dev, so sorry if I'm missing obvious iOS concepts here.
我有一个看起来像这样的JSON Feed:
I have a JSON feed that looks like:
{directory:[{id:0,fName:...,lName:...,标题 : ...... 部门 : ... BLD : ... 房间 : ... 电子邮件 : ...... 手机 : ... },{ ID :1,其中 fname : ... L-NAME : ... 称号 : ... 部门 : ... BLD : ... 房间 : ... 电子邮件 : ... 手机 : ...}]}
然后,我有一个Staff.h和.m,其中一个类具有与之匹配的属性(id,fName,lName)等。
Then, I have a Staff.h and .m with a class with properties to match it (id, fName, lName) ect.
我一直在这工作几个小时,但我似乎无法将JSON字符串解析为Staff对象数组。最终目标是让他们进入Core Data,所以任何建议都会很好。
I've been working at this for hours, but I can't seem to parse the JSON string to an array of Staff objects. The end goal is to get them into Core Data, so any advice would be nice.
我读过的教程没有展示如何使用JSON字符串{目录的形式:[{...}]}我在Android应用程序中执行此操作没有任何问题,但我在Objective-c中对iOS(6)的想法不合适。
Tutorials I've read haven't shown how to work with a JSON string in the form of {"directory":[{...}]} I had no problem doing this in my Android app, but I'm out of ideas here for iOS (6) in objective-c.
感谢阅读。
你可以这样做
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];
}
}
}