1

在我的 iOS 应用程序中,我必须解析一个 JSON 文件。从这个 JSON 中,我需要以下内容:名称、图像宽度和图像高度。要获取图像名称我没有任何问题,要获取图像和高度,我使用以下代码:

- (void) loadImageFromWeb:(NSString *)urlImg forName:(NSString*)name {
    NSURL* url = [NSURL URLWithString:urlImg];
    //NSURLRequest* request = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    NSString *authCredentials =@"reply:reply";
    NSString *authValue = [NSString stringWithFormat:@"Basic %@",[authCredentials base64EncodedStringWithWrapWidth:0]];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response,
                                               NSData * data,
                                               NSError * error) {
                               if (!error){
                                   UIImage* image = [[UIImage alloc] initWithData:data];
                                   imageWidth = image.size.width;
                                   imageHeight = image.size.height;
                                   imgWidth = [NSString stringWithFormat:@"%f", imageWidth];
                                   imgHeight = [NSString stringWithFormat:@"%f", imageHeight];
                                   self.dictWithDataForPSCollectionView = @{@"title": name,
                                                                            @"width": imgWidth,
                                                                            @"height": imgHeight};
                                   [self.arrayWithData addObject:self.dictWithDataForPSCollectionView];
                                   NSLog(@"DATA ARRAY: %@", self.arrayWithData);
                               } else {
                                   NSLog(@"ERRORE: %@", error);
                               }

                           }];
}

您可以看到我将名称、图像宽度和图像高度保存在 NSDictionary 中,然后将其放入 NSMutableArray 中。当它执行时NSLog,我看到了:

DATA ARRAY: (
        {
        height = "512.000000";
        title = "Eau de Toilet";
        width = "320.000000";
    },
        {
        height = "1049.000000";
        title = "Eau de Toilet";
        width = "1405.000000";
    }
)

我的问题是如何在调用我的 json 解析器的类中获取这些信息,我尝试以这种方式访问​​变量:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    recivedData = [[NSMutableData alloc]init];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [recivedData appendData:data];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"JSON: %@", string);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *json;
    NSError *err;

    json = [NSJSONSerialization JSONObjectWithData:recivedData options:NSJSONReadingMutableLeaves error:&err];
    JsonCategoryReader *reader = [[JsonCategoryReader alloc]init];
    [reader parseJson:json];
}

但是当我运行代码时,它会显示一个空数组。我怎样才能获得这堂课的信息?

更新:我要解析的 JSON 如下:

{
   "1":{
      "entity_id":"1",
      "type_id":"simple",
      "sku":"EAU_DE_TOILET_1",
      "description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
      "short_description":"EAU DE TOILETTE NATURAL SPRAY",
      "meta_keyword":null,
      "name":"Eau de Toilet",
      "meta_title":null,
      "meta_description":null,
      "regular_price_with_tax":60,
      "regular_price_without_tax":60,
      "final_price_with_tax":60,
      "final_price_without_tax":60,
      "is_saleable":true,
      "image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/p\/r\/product_100ml.png"
   },
   "2":{
      "entity_id":"2",
      "type_id":"simple",
      "sku":"EAU_DE_TOILET_2",
      "description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
      "short_description":"EAU DE TOILETTE NATURAL SPRAY",
      "meta_keyword":null,
      "name":"Eau de Toilet",
      "meta_title":null,
      "meta_description":null,
      "regular_price_with_tax":60,
      "regular_price_without_tax":60,
      "final_price_with_tax":60,
      "final_price_without_tax":60,
      "is_saleable":true,
      "image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/s\/c\/scheda_non_shop.jpg"
   }
}

我的方法parseJson执行以下操作:

- (void)parseJson:(NSDictionary *)jsonDict {

    // Controllo che il json sia stato ricevuto
    if (jsonDict) {
        self.nameArray = [[NSMutableArray alloc]init];
        self.imgUrlArray = [[NSMutableArray alloc]init];
        self.dictWithDataForPSCollectionView = [[NSDictionary alloc]init];
        self.arrayWithData = [[NSMutableArray alloc]init];
        [self createArrayWithJson:jsonDict andIndex:1];
        [self createArrayWithJson:jsonDict andIndex:2];
}

- (void)createArrayWithJson:(NSDictionary*)json andIndex:(NSString*)i {
    NSDictionary *products = [json objectForKey:i];
    NSString *name = [products objectForKey:@"name"];
    NSString *imgUrl = [products objectForKey:@"image_url"];
    // Scarico l'immagine e calcolo le dimensioni
    if (name != nil && imgUrl != nil) {
        [self loadImageFromWeb:imgUrl forName:name];
    }
}

我希望你明白我做了什么

4

1 回答 1

1

发生的情况是,您的类是在您的 json 下载之前制作的,因为有一个良好的序列,您必须调用您的方法来解析 completionHandler 块内的 json,当您确定它已下载时。然后当你加载你的对象时,你可以像这个例子一样解析它:

for (NSDictionary *dic in  reader.arrayWithData){

     NSLog("height:  %@",[dic objectForKey:@"height"]);
     NSLog("title: %@",[dic objectForKey:@"title"]);
     NSLog("width: %@",[dic objectForKey:@"width"]);

}
于 2013-11-11T10:31:51.417 回答