在我的iphone应用程序中解析objective-c中的json

时间:2012-06-04 08:18:05

标签: iphone objective-c json

我在解析我的iPhone应用程序的json数据时遇到问题,我是Objective-C的新手。我需要解析json并获取值以继续。请帮忙。这是我的JSON数据:

[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]

6 个答案:

答案 0 :(得分:1)

我建议使用JSONKit库进行解析。

这是关于如何使用它的tutorial。 您基本上会得到一本字典,并使用objectForKey和您的密钥来检索值。

答案 1 :(得分:1)

在iOS 5或更高版本上,您可以使用NSJSONSerialization。如果您将JSON数据包含在字符串中,则可以执行以下操作:

NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

修改要获取特定值:

NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:@"projName"];

答案 2 :(得分:1)

JSONKit

NSJSONSerialization(iOS 5.0或更高版本)

答案 3 :(得分:0)

我使用SBJson成功阅读和编写json。

查看documentation here并了解如何使用它。

基本上,对于解析,您只需将字符串提供给SBJsonParser,它就会返回一个带有objectForKey函数的字典。例如,您的代码可能类似于:

NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:@"projId"];

答案 4 :(得分:0)

使用SBJson

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];

答案 5 :(得分:0)

无需使用第三方课程。 Objective-c已经包含了处理JSON的功能。

NSJSONSerialization需要NSData个对象或从URL读取。以下是使用您的JSON字符串测试的:

NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData 
    options:NSJSONReadingAllowFragments error:&error] 

有关NSJSONSerialization的更多选项,请参阅documentation