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

时间:2022-12-01 18:13:25

I come from Android dev, so sorry if I'm missing obvious iOS concepts here.

我来自Android dev,如果我漏掉了明显的iOS概念,很抱歉。

I have a JSON feed that looks like:

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

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

{“目录”:[{ " id ":0,“帧”:“……”,“lName”:“……”,“标题”:“……”,“部门”:“……”,“梁式引线掐”:“……”,“房间”:“……”,“电子邮件”:“……”,“电话”:“…" },{ " id ":1、“帧”:“……”,“lName”:“……”,“标题”:“……”,“部门”:“……”,“梁式引线掐”:“……”,“房间”:“……”,“电子邮件”:“……”,“电话”:“……”}]}

Then, I have a Staff.h and .m with a class with properties to match it (id, fName, lName) ect.

然后,我有一根棍子。h和。m与一个具有属性匹配的类(id、fName、lName)。

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字符串解析为一组人员对象。最终的目标是将它们纳入核心数据,因此任何建议都是好的。

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.

我读过的教程没有展示如何以{"directory":[{…在我的Android应用程序中,我没有遇到过这样的问题,但是在objective-c中,我对iOS(6)没有什么想法。

Thanks for reading.

感谢你的阅读。

7 个解决方案

#1


17  

You can do it like

你可以这样做

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

#2


4  

Use: NSJSONSerialization

用途:NSJSONSerialization

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

使用NSJSONSerialization类将JSON转换为基础对象,并将基础对象转换为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.

You will get NSDictionary then you can parse (create) it to your object and then use it in CoreData.

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

#3


3  

Use following code:

使用以下代码:

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

This will covert json data onto NSDictionary, which is similar to hashmap on android. I think this will help you. :)

这将向NSDictionary中隐藏json数据,这类似于android的hashmap。我想这对你有帮助。:)

#4


2  

you can use NSJSonSerialisation or AFNetworking library. Here is the example of AFNetworking to parse json response

您可以使用NSJSonSerialisation或AFNetworking库。下面是解析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);
}]; 

then use Core Data framework to store data.

然后使用Core Data框架存储数据。

#5


1  

I would take a look at RestKit. It provides object-mapping and CoreData backed storage.

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

#6


1  

For this, you can SBJSON framework.

为此,您可以使用SBJSON框架。

You have to convert the response string into an NSDictionary like

您必须将响应字符串转换为类似NSDictionary的内容

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

Now you can create an object for Staff class.

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

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

Then you can store values in this object like

然后可以像这样在这个对象中存储值

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

Now you can pass this single object to other classes

现在可以将这个对象传递给其他类。

#7


1  

You can use the handmade solution proposed by @janak-nirmal, or use a library like jastor, https://github.com/elado/jastor, it doesn't make much difference. I warn you against Restkit, because the ratio benefits-vs-pain is very low, in my opinion. Moreover, it could be as use a tank to kill a fly in your scenario.

您可以使用@janak-nirmal提出的手工解决方案,或者使用jastor、https://github.com/elado/jastor之类的库,这没有多大区别。我警告你不要使用Restkit,因为在我看来,这种比率收益-收益-收益-痛苦的比率非常低。此外,它可以是在你的场景中使用坦克杀死一只苍蝇。

#1


17  

You can do it like

你可以这样做

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

#2


4  

Use: NSJSONSerialization

用途:NSJSONSerialization

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

使用NSJSONSerialization类将JSON转换为基础对象,并将基础对象转换为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.

You will get NSDictionary then you can parse (create) it to your object and then use it in CoreData.

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

#3


3  

Use following code:

使用以下代码:

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

This will covert json data onto NSDictionary, which is similar to hashmap on android. I think this will help you. :)

这将向NSDictionary中隐藏json数据,这类似于android的hashmap。我想这对你有帮助。:)

#4


2  

you can use NSJSonSerialisation or AFNetworking library. Here is the example of AFNetworking to parse json response

您可以使用NSJSonSerialisation或AFNetworking库。下面是解析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);
}]; 

then use Core Data framework to store data.

然后使用Core Data框架存储数据。

#5


1  

I would take a look at RestKit. It provides object-mapping and CoreData backed storage.

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

#6


1  

For this, you can SBJSON framework.

为此,您可以使用SBJSON框架。

You have to convert the response string into an NSDictionary like

您必须将响应字符串转换为类似NSDictionary的内容

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

Now you can create an object for Staff class.

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

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

Then you can store values in this object like

然后可以像这样在这个对象中存储值

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

Now you can pass this single object to other classes

现在可以将这个对象传递给其他类。

#7


1  

You can use the handmade solution proposed by @janak-nirmal, or use a library like jastor, https://github.com/elado/jastor, it doesn't make much difference. I warn you against Restkit, because the ratio benefits-vs-pain is very low, in my opinion. Moreover, it could be as use a tank to kill a fly in your scenario.

您可以使用@janak-nirmal提出的手工解决方案,或者使用jastor、https://github.com/elado/jastor之类的库,这没有多大区别。我警告你不要使用Restkit,因为在我看来,这种比率收益-收益-收益-痛苦的比率非常低。此外,它可以是在你的场景中使用坦克杀死一只苍蝇。