Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 获取Json解析后的数据_Ios_Objective C_Json - Fatal编程技术网

Ios 获取Json解析后的数据

Ios 获取Json解析后的数据,ios,objective-c,json,Ios,Objective C,Json,在我的iOS应用程序中,我必须解析一个JSON文件。从这个JSON中,我需要以下内容:名称、图像宽度和图像高度。要获取图像名称,我甚至没有任何问题,要获取图像的高度,我使用以下代码: - (void) loadImageFromWeb:(NSString *)urlImg forName:(NSString*)name { NSURL* url = [NSURL URLWithString:urlImg]; //NSURLRequest* request = [NSURLRequ

在我的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"
   }
}
- (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];
    }
}
我的方法
parseJson
执行以下操作:

{
   "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"
   }
}
- (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];
    }
}

我希望您理解我所做的

所发生的事情是,您的类在json下载之前就已经生成了,为了获得一个良好的序列,您必须在completionHandler块中调用您的方法来解析json,当您确定它已下载时。然后,当加载对象时,可以像下面的示例那样解析它:

for (NSDictionary *dic in  reader.arrayWithData){

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

}

发生的情况是,在下载json之前,您的类已经生成,为了获得一个良好的序列,您必须在completionHandler块中调用您的方法来解析json,当您确定它已下载时。然后,当加载对象时,可以像下面的示例那样解析它:

for (NSDictionary *dic in  reader.arrayWithData){

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

}


是否希望从服务hit类的外部获取响应数据?在使用arrayWithData中的数据之前,需要等待异步请求完成。“[reader parseJson:json];”有这样的同步吗?@Alex:我猜是这样,但是我怎么能等待这个请求呢?你可以在JsonCategoryReader中实现你自己的回调方法或块,或者如果“[reader parseJson:json];”在bg线程中使用。您可以使用同步映像加载。@Alex:您能在这里发布一个答案,并剪掉一段代码,以便我能更好地理解它吗?您想从服务hit类的外部获得响应数据,对吗?您需要等待异步请求完成,然后再使用arrayWithData中的数据。“[reader parseJson:json];”有这样的同步吗?@Alex:我猜是这样,但是我怎么能等待这个请求呢?你可以在JsonCategoryReader中实现你自己的回调方法或块,或者如果“[reader parseJson:json];”在bg线程中使用。你可以使用同步图像加载。@Alex:你能在这里发布一个答案,并剪掉一段代码,以便我能更好地理解它吗?它不起作用。。。事实上,如果我试图检查
阅读器.arrayWitData
中存储的内容,它就没有任何价值。我想这是因为我在另一个线程中填充了它……好吧,但是你的方法是parseJson:你能分享代码吗?我现在读了,但是我如何解决这个问题呢?如果我这样做你会怎么想:1。从第一个类2调用方法
parseJson
。使用第二个类3解析Json。将名称和图像url 4传递给第一个类。在第一个类中,我连接到pic以获取高度和宽度?当您创建对象读取器时,您必须使用loadImageFromWeb:forName:来加载它,或者使用您的get-nil对象,因为我们内部没有任何内容,所以无法工作。。。事实上,如果我试图检查
阅读器.arrayWitData
中存储的内容,它就没有任何价值。我想这是因为我在另一个线程中填充了它……好吧,但是你的方法是parseJson:你能分享代码吗?我现在读了,但是我如何解决这个问题呢?如果我这样做你会怎么想:1。从第一个类2调用方法
parseJson
。使用第二个类3解析Json。将名称和图像url 4传递给第一个类。在第一个类中,我连接到pic以获得高度和宽度?当您创建对象读取器时,您必须使用loadImageFromWeb:forName:来加载它,或者使用您的get-nil对象,因为我们内部没有任何内容