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

时间:2013-12-04 12:08:31

标签: ios objective-c json

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

我有一个类似的JSON Feed:

{"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中的想法。

感谢阅读。

7 个答案:

答案 0 :(得分:17)

你可以这样做

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];
        }
    }
}

答案 1 :(得分:4)

使用:NSJSONSerialization

  

您使用NSJSONSerialization类将JSON转换为Foundation   对象并将Foundation对象转换为JSON。

An object that may be converted to JSON must have the following properties:

The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.

您将获得NSDictionary,然后您可以将其解析(创建)到您的对象,然后在CoreData中使用它。

答案 2 :(得分:3)

使用以下代码:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

这会将json数据转换为NSDictionary,类似于android上的hashmap。我想这会对你有所帮助。 :)

答案 3 :(得分:2)

您可以使用NSJSonSerialisationAFNetworking库。以下是解析json响应的AFNetworking示例

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
    NSDictionary *json = (NSDictionary *)responseObject;
    NSArray *staffArray = json[@"directory"];

[staffArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop){
      Staff *staff = [[Staff alloc] init];
    staff.id = [[obj objectForKey:@"id"] integerValue];
    staff.fname = [obj objectForKey:@"fName"];
    staff.lname = [obj objectForKey:@"lName"]; 

   //add data to new array to store details
   [detailsArray addObect:staff);
} ];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}]; 

然后使用Core Data framework存储数据。

答案 4 :(得分:1)

我会看看RestKit。它提供了对象映射和CoreData支持的存储。

答案 5 :(得分:1)

为此,您可以SBJSON框架。

您必须将响应字符串转换为NSDictionary,如

 NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [responseString JSONValue];

现在,您可以为员工类创建一个对象。

Staff *staff = [[Staff alloc]init];

然后您可以在此对象中存储值,如

staff.firstname = [[[dic objectForKey:@"directory"] objectAtIndex:0] objectForKey:@"fName"];

现在您可以将此单个对象传递给其他类

答案 6 :(得分:1)

您可以使用@ janak-nirmal提出的手工制作的解决方案,或使用像jastor,https://github.com/elado/jastor这样的库,它没有多大区别。 我警告你不要使用Restkit,因为在我看来,益处与痛苦的比例非常低。 而且,在你的场景中可以使用坦克来杀死一只苍蝇。