将JSON响应转换为数组

时间:2014-10-12 19:47:14

标签: ios objective-c json

我目前正在构建我的第一个iOS应用。作为此应用程序的一部分,我需要从Web服务器获取一些数据。以下功能是其中的一部分:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    // show all values
    for(id key in res) {

        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

}

这将通过它获取的JSON数据(您可以在下面看到一个数据示例)。但是,为了能够将其放入表格视图中,我需要将其转换为NSArray。像这样:

self.array = [[NSArray alloc] initWithObjects:
    @"Always put your fears behind you and your dreams in front of you.",
    @"A relationship with no trust is like a cell phone with no service, all you can do is play games.",
    @"People should stop talking about their problem and start thinking about the solution.",
    @"Dear Chuck Norris, Screw you. I can grill burgers under water. Sincerely, Spongebob Squarepants.",
    @"My arms will always be open for you, they will never close, not unless you're in them.",
    nil];

正如所承诺的,这是来自服务器的数据--JSON响应:

{"data": "[

     {"TVShow1":"Dexter", "Episodes":"125"},
     {"TVShow2":"Boardwalk Empire", "Episodes":"54"},   
     {"TVShow3":"Fargo", "Episodes":"10"},   
     {"TVShow1":"The Sopranos", "Episodes":"11"}

]"}

如何将其更改为NSArray

2 个答案:

答案 0 :(得分:1)

你不必改变任何事情。

您的json是一个包含数组的对象,在您的情况下称为data

NSArray *data = [res objectForKey:@"data"];//for sake of demo but should be a property
NSLog(@"",data);//that's your data source

然后在cellAtIndexRow委托中,阅读值:

cell.textLabel.text = data[indexPath.row][@"Episodes"];//that will display episode

答案 1 :(得分:1)

如图所示,

NSJSONSerialization会将其转换为NSDictionary。从那里,只需使用data键访问数组:

NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

NSArray *data = res[@"data"];
if (!data) {

    NSLog(@"Error: no data array was found.");

}

// do something with the data array