首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Json解析后获取数据

Json解析后获取数据
EN

Stack Overflow用户
提问于 2013-11-11 10:20:31
回答 1查看 178关注 0票数 1

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

代码语言:javascript
复制
- (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时,我看到以下内容:

代码语言:javascript
复制
DATA ARRAY: (
        {
        height = "512.000000";
        title = "Eau de Toilet";
        width = "320.000000";
    },
        {
        height = "1049.000000";
        title = "Eau de Toilet";
        width = "1405.000000";
    }
)

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

代码语言:javascript
复制
-(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如下:

代码语言:javascript
复制
{
   "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执行以下操作:

代码语言:javascript
复制
- (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];
    }
}

我希望你能理解我的所作所为

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-11 10:31:51

所发生的事情是在json下载之前创建类,因为如果您确定json是下载的,那么必须调用您的方法来解析completionHandler块中的json。然后,当您加载对象时,可以像下面这样解析它:

代码语言:javascript
复制
for (NSDictionary *dic in  reader.arrayWithData){

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

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19903902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档