我不了解如何在Xcode中使用JSON数据

时间:2014-10-20 18:29:02

标签: objective-c json

我已成功下载并解析(我认为)JSON数据

NSURL *quoteURL = [NSURL URLWithString:@"http://www.qwoatzz.com"];

NSData *jsonData = [NSData dataWithContentsOfURL:quoteURL];

NSError *error = nil;

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; 

但是,我不太确定如何实际使用JSON数据。如果JSON文件有一个包含两个键的数组,如何从特定索引(例如第一个)的其中一个键获取值,并使用它来更改标签的文本(我知道如何做到这一点) ,它只是我坚持的JSON部分)?

2014-10-20 19:46:10.616 Qwoatz-2[3147:454481] dataDictionary : {
    count = 10;
    "count_total" = 1871;
    pages = 188;
    posts =     (
                {
            author = "Jason Seifer";
            date = "2014-10-20 13:54:11";
            id = 24317;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/1634685862_92b26b9167_o-150x150.jpg";
            title = "What Employers Are Looking For in a Junior Rails Developer";
            url = "http://blog.teamtreehouse.com/employers-looking-junior-rails-developer";
        },
                {
            author = "Zac Gordon";
            date = "2014-10-16 09:27:38";
            id = 24296;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/brochure-site-150x150.png";
            title = "When is WordPress.com the Right Solution?";
            url = "http://blog.teamtreehouse.com/wordpress-com-right-solution-website";
        },
                {
            author = "Gill Carson";
            date = "2014-10-15 12:52:43";
            id = 24287;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/Tahoe_team-Photo-150x150.jpg";
            title = "We Are Family – The Whole Team!";
            url = "http://blog.teamtreehouse.com/family";
        },
                {
            author = "Jason Seifer";
            date = "2014-10-14 15:26:11";
            id = 24292;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/Chartist-Simple-responsive-charts-2014-10-14-15-24-43-150x150.jpg";
            title = "Responsive Charts";
            url = "http://blog.teamtreehouse.com/responsive-charts";
        },
                {
            author = "Guil Hernandez";
            date = "2014-10-13 09:28:05";
            id = 24228;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/09/blend-mode-mult-150x150.jpg";
            title = "Cutting-Edge CSS Features You Can Use Today";
            url = "http://blog.teamtreehouse.com/cutting-edge-css-features-can-use-today";
        },
                {
            author = "Faye Bridge";
            date = "2014-10-10 09:00:45";
            id = 24230;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/09/Nick-Bryan-150x150.jpg";
            title = "After Just 6 Months Learning Nick is a full-time Web Developer";
            url = "http://blog.teamtreehouse.com/6-months-nick-now-full-time-web-developer-major-computing-firm";
        },
                {
            author = "Pasan Premaratne";
            date = "2014-10-09 13:59:23";
            id = 24250;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/Screen-Shot-2014-10-06-at-5.57.16-PM-150x150.png";
            title = "Making a Network Request in Swift";
            url = "http://blog.teamtreehouse.com/making-network-request-swift";
        },
                {
            author = "Zac Gordon";
            date = "2014-10-09 09:21:29";
            id = 24278;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/wordpress_themes-150x150.jpg";
            title = "New Course: WordPress Theme Development";
            url = "http://blog.teamtreehouse.com/new-course-wordpress-theme-development";
        },
                {
            author = "Dave McFarland";
            date = "2014-10-08 13:47:55";
            id = 24255;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/Screen-Shot-2014-10-06-at-1.02.40-PM-150x150.png";
            title = "How to Install Node.js and NPM on a Mac";
            url = "http://blog.teamtreehouse.com/install-node-js-npm-mac";
        },
                {
            author = "Jason Seifer";
            date = "2014-10-07 16:15:00";
            id = 24273;
            thumbnail = "http://blog.teamtreehouse.com/wp-content/uploads/2014/10/html5-device-mockups-150x150.jpg";
            title = "Device Mockups";
            url = "http://blog.teamtreehouse.com/device-mockups";
        }
    );
    status = ok;
}

已解析的示例JSON文件。

3 个答案:

答案 0 :(得分:2)

循环通过字典:

for(NSString *key in dataDictionary) {
    id myObject = [dataDictionary objectForKey:key];
    //do something with myObject
}

NSDictionary不是有序集合,因此无法保证如上所示循环遍历字典将始终以相同的顺序循环键。使用Cocoa / Cocoa Touch的Apple doesn't provide an ordered dictionary,并且通常将NSDictionary或NSMutableDictionary子类化为一个坏主意,因为它们是class cluster的一部分。

查看示例中的文本,posts实际上是一个充满字典的数组。假设您的示例中的所有键在您将要获取的JSON文件中保持不变,您可以使用

检索它。
NSArray *posts = [dataDictionary arrayForKey:@"posts"];

此数组似乎已按日期排序。然后,您可以获得每个帖子的标题

for(int i = 0; i < [posts count]; i++) {
    NSString *title = [((NSDictionary *)(posts[i])) objectForKey:@"title"];
    //do something with title
}

答案 1 :(得分:1)

1)您知道数据是数组吗?

  • JSON文件有一个包含两个键的数组,......
  • 来自特定索引的其中一个键的值...

这对我来说有点混淆。当我有一个JSON数组或NSArray时,我倾向于只考虑索引(因为这是如何排序数组的),当我有JSON对象或NSDictionaries时,我倾向于想到

那么,返回值是这样的:

[ "cat", 1, "a" ]

或者数据是这样的:

{ "cat": { "count": 1, "tag": "a" } }

第一个例子是一个包含3个元素的数组;第二个是具有1个成员的对象,其本身有2个成员。

2)如果数据被正确解析为NSArray或NSDictionary ......

然后,您只需要提取所需的数据,并在任一容器上提供访问器。

E.g。

NSArray *a = ... [a firstObject]; [a objectAtIndex:0]; // same as above

NSDictionary *d = ... d[@"memberName"]; [d objectForKey:@"memberName"]; // same as above

您希望实际保存该数据,或将其传递给处理,而不是仅仅调用访问者。

更新:基于问题中更新的示例数据。

一种方法是您可以手动和迭代地提取数据。

NSDictionary *dataDictionary = ...
NSInteger count = [[dataDictionary objectForKey:@"count"] integerValue];
NSInteger countTotal = [[dataDictionary objectForKey:@"count_total"] integerValue];
NSInteger pagesCount = [[dataDictionary objectForKey:@"pages"] integerValue];
NSString *status = [dataDictionary objectForKey:@"status"];
NSArray *posts = [dataDictionary objectForKey:@"posts"];

for (NSDictionary *post in posts) {
    for (NSString *key in post) {
        NSLog(@"%@: %@", key, post[key]);
    }
}

当您记录dataDictionary时,明确字符串的不带引号的元素是字符串,引号中的元素是字符串,整数和其他数字可能是可用的数字,但它们可能是字符串(取决于返回格式),日期将是字符串(你可以使用NSDate和NSDateFormatter来打印它),状态只是一个字符串;对于帖子,&#39;(&#39;和&#39;)&#39;包装一个数组,&#39; {&#39;,&#39;}&#39;包裹字典。

更新2:

如果您真的想进行高级搜索,可以使用NSPredicate来过滤NSDictionary或NSArray。例如,类似下面的内容可行:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSDictionary *data = @{
            @"stuff": @1,
            @"posts": @[
                @{ @"id": @1, @"title": @"one" },
                @{ @"id": @2, @"title": @"two" },
                @{ @"id": @3, @"title": @"three" },
                @{ @"id": @4, @"title": @"four" },
                @{ @"id": @5, @"title": @"five" },
            ]
        };

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.id == %@", @4];
        NSString *title = [[data[@"posts"] filteredArrayUsingPredicate:predicate] firstObject];
        NSLog(@"title: %@", title);
    }
}

打印

title: {
    id = 4;
    title = four;
}

答案 2 :(得分:0)

您可以使用JSONModel Framework

JSONModel是iOS和OSX的数据模型框架。它是用Objective-C编写的,可以通过几种不同的方式为您提供帮助。

您可以在下面详细了解其主要功能:

  • 快速编写模型代码
  • 验证模型的输入
  • 原子数据
  • JSON和Obj-C之间的类型转换
  • 内置数据转换器
  • 自定义数据转换器
  • 模型级联
  • 转换回&amp;来自/来自JSON
  • 在内存或文件中保留模型状态
  • 直接从互联网创建模型
  • 自动模型比较方法

注意请确保您的媒体资源名称与JSON中的密钥名称匹配

JSONModel Framework

GitHub Link