繁体   English   中英

如何解析 JSON 数据并在 iphone 应用程序中显示内容

[英]how to parse JSON data and show content in iphone app

我想要阵列中的 object 如何将它们存储在 object 中,就像我使用时一样

myArray.id=
myArray.name=

所以它会显示值

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=categories&appid=620&mainonly=true"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];

这里有一个很棒的教程,关于如何解析 JSON 由 Matt Gallagher 撰写。 希望这能让你朝着正确的方向开始。

以下应显示您的代码/JSON 的结果:

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];

// the JSON response is an Array
NSArray *results = [parser objectWithString:json_string error:nil];
NSDictionary *dictOne = [results objectAtIndex:0];
NSArray *activitiesArray = [dictOne objectForKey:@"activities"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSDictionary *eventDict = [dictTwo objectForKey:@"event"];

NSLog(@"%@ - %@", [eventDict objectForKey:@"category"]);

从 json 调用数据时,您需要注意一些事项,但这很容易。 首先,您应该在 m 文件的顶部添加这两行:

#define kAsyncModus dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kYourJsonURL [NSURL URLWithString: @"_THE_JSON_URL_"]

然后,将以下部分插入到您的 viewDidLoad 方法中。 “dispatch_async”必须与之前定义的宏(在顶部)一起使用,以便您创建一个线程。 否则,如果服务器没有响应但该方法一直在等待它,您的应用程序可能会崩溃。

// get elements of json
dispatch_async(kAsyncModus, ^{
    NSData *data = [NSData dataWithContentsOfURL: kYourJsonURL];
    [self performSelectorOnMainThread:@selector(fetchedData:)
                           withObject:data
                        waitUntilDone:YES];
});       

并创建一个新方法,从收到的 json 中获取单个元素

- (void)fetchedData:(NSData *)responseData{
    NSError *error;
    NSDictionary *json =
    [NSJSONSerialization JSONObjectWithData:responseData
                                    options:kNilOptions
                                      error:&error];

    NSArray *results = [json objectForKey:@"_firstElementInJsonFile_"];


    NSLog(@"Results: %@", results);

}

有关更多详细信息,请使用结果

NSDictionary *specificData = [results objectAtIndex:0];

并且应该这样做。

我只是用最短的方式解释了它,如果你想让所有的事实看下面的教程 但我不确定,是否支持使用 < iOS5 的旧设备。 在知道之前我无法测试它。 如果你需要这样的东西,也许你可以看看 Git 上的 JSONKit。 也许有人知道这些细节,对我来说也很有趣。

json 框架是通往 go 的方式。

但是,此 JSON 无效。 告诉提供 API 的人,以确保他们的 JSON 退货有效

JSONKit 使这很容易,可能值得考虑。 而且速度非常快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM