【问题标题】:How to output JSon data in Objective-C如何在 Objective-C 中输出 JSON 数据
【发布时间】:2012-07-09 13:54:25
【问题描述】:

我目前正在开发一个从以下来源获取数据的 iPhone 应用程序:

我正在尝试弄清楚如何在文本字段中将其解析为人类可读的格式。

到目前为止我的代码是:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *urlString = [NSString stringWithFormat:@"http://dev.threesixtyapp.com/api/events.php?action=available&id=1"];
    NSURL *url =[NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSError  *error;
    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSLog(@"%@",json);
}

【问题讨论】:

    标签: iphone objective-c json


    【解决方案1】:

    http://stig.github.com/json-framework/ - SBJson 是一个很棒的 JSON 编码/解码框架。我建议您检查一下...它将为您解析为 NSDictionary,您只需将文本字段的文本设置为您想要的 NSDictionary 中的值。使用这个框架非常简单。当您将 Json 传递给 SBJson 函数时,您的 Json 应该只是一个字符串

    【讨论】:

    • 速度要快得多。甚至比 Apple 的原生 plist 序列化/反序列化还要快。在他们的项目页面上查看速度比较!
    【解决方案2】:

    首先你要了解你的json的数据结构。
    您可以使用JSON Viewer查看您的json的数据结构。
    如我所见,您正在获取由event_titledate_fromdate_to 组成的对象数组。

    NSError *error = nil;
    NSArray *jsonArry = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSLog(@"%@",jsonArry);
    for (NSDictionary *dict in jsonArry) {
        NSString * title = [dict objectForKey:@"event_title"];
        NSString * dateTo = [dict objectForKey:@"date_to"];
        NSString * dateFrom = [dict objectForKey:@"date_from"]; 
        NSLog(@"title=%@,dateTo=%@,dateFrom=%@",title,dateTo,dateFrom);
    }
    

    【讨论】:

    • @AviramNetanel 我已经更新了我的答案。 NSError *error = nil;
    猜你喜欢
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多