从数组中的数组中获取JSON数据

时间:2014-05-08 12:17:29

标签: ios objective-c json

我试图找出如何从另一个数组中的JSON数组中获取数据。

这是JSON。我想从照片中获取一张图片网址。

[

    {
        "id":6901439,
        "name":"INDTTIN CD",
        "description":"Full-length released June 2013 via Little Heart Records. \r\n\r\nTrack Listing:\r\n\r\n1. Tired\r\n2. Time to Heal\r\n3. Gypsy Summer\r\n4. Sketchbooks\r\n5. I Never Deserve the Things I Need\r\n6. Say it With the \"I\"\r\n7. A Negative Mind\r\n8. Rafters\r\n9. Indrid Cold\r\n10. Present Tense ",
        "short_url":"http://onmyhonor.storenvy.com/products/6901439-indttin-cd",
        "status":"active",
        "labels":null,
        "preorder":false,
        "on_sale":true,
        "store_id":373949,
        "price":"7.00",
        "marketplace_category":"music-cds",
        "marketplace_category_id":345,
        "photos":[
            {
                "photo":{
                    "original":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_original.jpg",
                    "large":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_large.jpg",
                    "homepage":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_homepage.jpg",
                    "medium":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_medium.jpg",
                    "small":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_small.jpg",
                    "64w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_64w.jpg",
                    "200w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_200w.jpg",
                    "400w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_400w.jpg",
                    "600w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_600w.jpg",
                    "1000w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_1000w.jpg",
                    "64sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_64sq.jpg",
                    "200sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_200sq.jpg",
                    "400sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_400sq.jpg"
                }
            }
        ],
        "variants":[
            {
                "variant":{
                    "id":14382188,
                    "name":"INDTTIN CD",
                    "position":1,
                    "sku":"",
                    "full_quantity":300,
                    "in_stock":300,
                    "percent_available":100,
                    "is_default_variant?":false,
                    "price":7.0,
                    "sold_out":false,
                    "status":"active"
                }
            }
        ],
        "collections":[
        ],
        "store":{
            "id":373949,
            "name":"On My Honor",
            "marketplace_url":"http://www.storenvy.com/stores/373949-on-my-honor"
        }
    }

]

这是我的代码:

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: @"http://onmyhonor.storenvy.com/products.json"]

#import "GRSStoreViewController.h"
#import "GRSStoreDetailViewController.h"

@interface GRSStoreViewController ()

@end

@implementation GRSStoreViewController
@synthesize name, description, short_url, price, productImage, nameArray, descriptionArray, urlArray, priceArray, imageArray, url;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Store";

    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];

    url = [NSURL URLWithString:@"http://onmyhonor.storenvy.com/products.json"];

    dispatch_async(kBgQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });
}

- (void)fetchedData:(NSData *)responseData
{
    NSError *error;
    nameArray = [[NSMutableArray alloc]init];
    descriptionArray = [[NSMutableArray alloc]init];
    urlArray = [[NSMutableArray alloc]init];
    priceArray = [[NSMutableArray alloc]init];
    imageArray = [[NSMutableArray alloc]init];

    NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    for (NSDictionary *item in json)
    {
        name = [item objectForKey:@"name"];
        description = [item objectForKey:@"description"];
        short_url = [item objectForKey:@"short_url"];
        price = [item objectForKey:@"price"];
        [nameArray addObject:name];
        [descriptionArray addObject:description];
        [urlArray addObject:short_url];
        [priceArray addObject:price];
    }
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [nameArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
        cell.textLabel.font = [UIFont systemFontOfSize:16.0];
    }

    if (cell)
    {
        cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];
        cell.textLabel.textColor = [UIColor darkGrayColor];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GRSStoreDetailViewController *itemDetail = [[GRSStoreDetailViewController alloc]initWithNibName:@"GRSStoreDetailViewController" bundle:nil];
    itemDetail.priceString = [priceArray objectAtIndex:indexPath.row];
    itemDetail.descriptionString = [descriptionArray objectAtIndex:indexPath.row];
    itemDetail.itemURL = [urlArray objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:itemDetail animated:YES];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

2 个答案:

答案 0 :(得分:1)

将循环更改为

for (NSDictionary *item in json)
{
    NSArray *photos = item[@"photos"];
    NSDictionary *dict = [photos[0] valueForKeyPath:"photo"];
    NSLog(@"original = %@", dict[@"original"]);


    name = [item objectForKey:@"name"];
    description = [item objectForKey:@"description"];
    short_url = [item objectForKey:@"short_url"];
    price = [item objectForKey:@"price"];
    [nameArray addObject:name];
    [descriptionArray addObject:description];
    [urlArray addObject:short_url];
    [priceArray addObject:price];
}

答案 1 :(得分:1)

更改此

NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    for (NSDictionary *item in json)
    {
        name = [item objectForKey:@"name"];
        description = [item objectForKey:@"description"];
        short_url = [item objectForKey:@"short_url"];
        price = [item objectForKey:@"price"];
        [nameArray addObject:name];
        [descriptionArray addObject:description];
        [urlArray addObject:short_url];
        [priceArray addObject:price];
    }
    [self.tableView reloadData];

到此

NSdictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

  name = [json objectForKey:@"name"];
  description = [json objectForKey:@"description"];
  short_url = [json objectForKey:@"short_url"];
  price = [json objectForKey:@"price"];

  // this is your photos array
  NSArray *photos = [josn objectForKey:@"photos"];
  // every object in this array is a dictionary. In your case this array has only one dictionary so
  NSDictionary *photosDict = [photos firstObject];
  // from here you can access all keys of photosDict

photosDict中的所有可用键:

  • 原始
  • 主页
  • 介质
  • 64瓦特
  • 200瓦特
  • 400瓦特
  • 600瓦特
  • 千瓦特
  • 64sq
  • 200sq
  • 400sq