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]]];
11
  • what the result u get here productname Commented Jan 29, 2016 at 12:21
  • yes sir, i am getting error in debug area after crashing the app like:- "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7961dbe0' " Commented Jan 29, 2016 at 12:23
  • you are getting product name as string right? After that you need to get the dictionary then you will be able to show in collection view as "data" array Commented Jan 29, 2016 at 12:23
  • ya correct what the answer you want to shown in your collectionview Commented Jan 29, 2016 at 12:23
  • yes sir product name as string and id as integer Commented Jan 29, 2016 at 12:23

3 Answers 3

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];
Sign up to request clarification or add additional context in comments.

5 Comments

should i place this code inside did receive method "NSDictionary *dictn=[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error]; NSArray *arr_data = [dictn objectForKey:@"data"]; "
No in connectionDidFinishLoading
how will i add dictionary object image name in the url and thanks download that image.?
@ReshmiMajumder, give me some suggestions please
sorry! but I am unable to understand your querry "how will i add dictionary object image name in the url and thanks download that image.?"
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;

        }

12 Comments

Thanks for your response sir, i tried to follow your answer
ya it works , in my small suggestion in here use tableview no need of collection View
yes sir thank for suggestion, but client want it like in grid view so i need to implement collectionview
you always rock sir, now i am getting data correctly just little issues are there now, i will back to you sir if i have any issue.
Hello sir, i am having trouble for download image.?
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.