在 iOS 中,如何将 JSON 字符串解析为对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20374986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In iOS, how do I parse a JSON string into an object
提问by whoknows
I come from Android dev, so sorry if I'm missing obvious iOS concepts here.
我来自 Android 开发人员,很抱歉,如果我在这里遗漏了明显的 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":"..."}]}
{"directory":[{"id":0,"fName":"...","lName":"...","title":"...","dept":"...","bld":"...","room":"...","email":"...","phone":"..."},{"id":1,"fName":"...","lName":"...","title":"...","dept":"...","bld":"...","room":"...","email":"...","phone":"..."}]}
Then, I have a Staff.h and .m with a class with properties to match it (id, fName, lName) ect.
然后,我有一个 Staff.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 字符串解析为 Staff 对象数组。最终目标是让它们进入 Core Data,所以任何建议都会很好。
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":[{...}]} 形式的 JSON 字符串我在我的 Android 应用程序中这样做没有问题,但我已经用完了此处针对 Objective-c 中的 iOS (6) 的想法。
Thanks for reading.
谢谢阅读。
回答by Janak Nirmal
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];
}
}
}
回答by Anoop Vaidya
Use: NSJSONSerialization
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to 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.
您可以使用 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.
You will get NSDictionary then you can parse (create) it to your object and then use it in CoreData.
您将获得 NSDictionary,然后您可以将其解析(创建)到您的对象,然后在 CoreData 中使用它。
回答by Abdullah Md. Zubair
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. :)
这会将 json 数据转换到 NSDictionary 上,这类似于 android 上的 hashmap。我认为这会对你有所帮助。:)
回答by Suhit Patil
you can use NSJSonSerialisation
or AFNetworkinglibrary. Here is the example of AFNetworking to parse json response
您可以使用NSJSonSerialisation
或AFNetworking库。这是 AFNetworking 解析 json 响应的示例
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 framework
存储数据。
回答by Giordano Scalzo
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,因为在我看来,收益与痛苦的比率非常低。此外,它可能就像在您的场景中使用坦克杀死苍蝇一样。
回答by manujmv
For this, you can SBJSONframework.
为此,您可以使用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 Staffclass.
现在您可以为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
现在您可以将这个单个对象传递给其他类