0

I am working with json parsing using nsserialization. i have a json data and i want to parse it in uicollectionview. this is my json api data.

{
  "result": "Successful",
  "data": [
    {
      "id": "2",
      "product_name": "6\" Round Plate",
      "sku": "ECOW6RP",
      "description": "Ideal for serving finger foods and snacks. The safe and healthy serving option. Made from 100% sugarcane pulp, these plates can be used in microwaves and freezers. \r\n\r\nDiameter 6.0 (inch) x Depth 0.6 (inch)",
      "price": "100.00",
      "business_price": "90.00",
      "image": "14531965421452838128ecow6rp_02.jpg",
      "pack_size": "10",
      "business_pack_size": "50",
      "category": "2,3",
      "tax_class": "1",
      "created": "2016-01-19",
      "altered": "2016-01-21 11:13:42",
      "status": "1",
      "deleted": "0"
    },
    {
      "id": "3",
      "product_name": "Bio Bags (Large)",
      "sku": "ECOWGBL",
      "description": "Bio Bags (Large) Description ",
      "price": "100.00",
      "business_price": "90.00",
      "image": "14531967251452837823ECOWGBS_03.jpg",
      "pack_size": "10",
      "business_pack_size": "50",
      "category": "2,3",
      "tax_class": "1",
      "created": "2016-01-19",
      "altered": "2016-01-21 11:14:37",
      "status": "1",
      "deleted": "0"
    },
    {
      "id": "4",
      "product_name": "Bio Bags (Medium)",
      "sku": "ECOWGBM",
      "description": "Bio Bags (Medium) Description \r\n",
      "price": "100.00",
      "business_price": "90.00",
      "image": "14531968711452837959ECOWGBM_03.jpg",
      "pack_size": "10",
      "business_pack_size": "50",
      "category": "2,3",
      "tax_class": "1",
      "created": "2016-01-19",
      "altered": "2016-01-21 11:14:47",
      "status": "1",
      "deleted": "0"
    },
    {
      "id": "5",
      "product_name": "Bio Bags (Small)",
      "sku": "ECOWGBS",
      "description": "Bio Bags (Small) Description",
      "price": "74.00",
      "business_price": "64.00",
      "image": "14531969571452838088ECOWGBL_02.jpg",
      "pack_size": "10",
      "business_pack_size": "50",
      "category": "2,3",
      "tax_class": "1",
      "created": "2016-01-19",
      "altered": "2016-01-21 11:14:59",
      "status": "1",
      "deleted": "0"
    },
    {
      "id": "6",
      "product_name": "7\" Round Plate",
      "sku": "ECOW7RP",
      "description": "Ideal for serving finger foods and snacks. The safe and healthy serving option. Made from 100% sugarcane pulp, these plates can be used in microwaves and freezers. \r\n\r\nDiameter 7.2 (inch) x Depth 0.6 (inch)",
      "price": "100.00",
      "business_price": "90.00",
      "image": "14531971831452838830ecow7rp_01.jpg",
      "pack_size": "10",
      "business_pack_size": "50",
      "category": "2,3",
      "tax_class": "1",
      "created": "2016-01-19",
      "altered": "2016-01-21 11:14:17",
      "status": "1",
      "deleted": "0"
    }
  ]
}

This is my json data now i want to parse only product_name, id, image in uicollectionview cell. this is my code below.

- (void)viewDidLoad {
  [super viewDidLoad];

  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  NSURL *url =  [NSURL URLWithString:@"http://dev1.brainpulse.org/ecoware1/webservices/products/2"];
  NSURLRequest *request= [NSURLRequest requestWithURL:url];
  [NSURLConnection connectionWithRequest:request delegate:self];
  _collectionview.delegate = self;
  _collectionview.dataSource = self;
}

-(void)connection:(NSURLConnection *)connection   didReceiveResponse:(nonnull NSURLResponse *)response{
  data = [[NSMutableData alloc] init];
  NSLog(@"Did receive response");
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata{
  [data appendData:thedata];
  NSLog(@"daata");
}

-(void)connectionDidFinishLoading:(NSURLConnection  *)connection {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  productname = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  [_collectionview reloadData];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  UIAlertView *errorview= [[UIAlertView alloc]initWithTitle:@"Error" message:@"The download could not complete please make sure you're connected to internet" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
  [errorview show];
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  return [productname count];
}

-(UICollectionViewCell*)collectionView:(UICollectionView   *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  OneTimeCell *cell = (OneTimeCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  // cell.productname.text = [[productname    objectAtIndex:indexPath.row] objectForKey:@"product_name"];
  NSArray *myArr = [productname objectAtIndex:indexPath.row];
  cell.productname.text = [[myArr objectAtIndex:0] objectForKey:@"result"];
  return cell;
}

i want to update image directly from the url, i make a url by adding a object key for image and wan to parse that image on my image view please see my code below

 NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:@"image" ];
NSLog(@"image  %@", image);

NSURL *baseURL = [NSURL URLWithString:@"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSURL *absURL = [url absoluteURL];
NSLog(@"absURL = %@", absURL);



    cell.productimage.image = [UIImage imageWithData:[NSData     dataWithContentsOfURL:[NSURL URLWithString:absURL]]];
sandeep tomar
  • 303
  • 1
  • 5
  • 17

3 Answers3

2

indexPath.row Use this

NSDictionary *dictn=[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

NSArray *arr_data = [dictn objectForKey:@"data"];

// In cellForItemAtIndexPath collectionviewcell delegate

NSDictionary *one_object = [arr_data objectAtIndex:indexPath.row];
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Reshmi Majumder
  • 961
  • 4
  • 15
1

You're referencing the productName dictionary, and I'm guessing what you want to access is the array embedded within it.

In your didFinishLoading method, pull out the array like this:

NSDictionary * someDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
productname = someDictionary[@"data"];

Then, in your cellForItemAtIndexPath method, pull out the bits you want:

NSDictionary * cellData = productName[indexPath.row]; //refers to the cell at that index
NSString * product_nameString = cellData[@"product_name"];
NSString * description = cellData[@"description"]; //etc
cell.productName.text = product_nameString;

You can tell what's a dictionary, and what's an array in your JSON by looking at the brackets. { } == dictionary / object, [ ] == array. Access arrays with an index and dictionaries with a key. It looks like 'data' is just an array of dictionaries.

Johnny Rockex
  • 4,136
  • 3
  • 35
  • 55
1

Step-1

allocate the memory of your NSMutableArray in ViewDidLoad, like this

- (void)viewDidLoad {
 [super viewDidLoad];

productname = [NSMutableArray New];
}

Step-2

  -(void)connectionDidFinishLoading:(NSURLConnection  *)connection
  {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *arr = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"data"];

   [productname removeAllObjects];

    for (NSDictionary *tmp in arr)
   {
   NSMutableDictionary *temp = [NSMutableDictionary New];
   [temp setObject:[tmp objectForKey:@"product_name"] forKey:@"product_name"];
   [temp setObject:[tmp objectForKey:@"id"] forKey:@"id"];
   [temp setObject:[tmp objectForKey:@"image"] forKey:@"image"];

   [productname addObject:temp];

   }
  if (productname)
 {
 [_collectionview reloadData];
 }

  }

Step-3

   -(UICollectionViewCell*)collectionView:(UICollectionView   *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

OneTimeCell *cell = (OneTimeCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];


cell.productname.text = [[productname objectAtIndex:indexPath.row] objectForKey:@"product_name"];


return cell;

        }
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143