Reputation: 445
I've done the Raywenderlich tutorial about JSON in iOS but I got difficulties to adapt it to my own JSON file. Here is my JSON:
{
"Albumvideo":[
{
"titre": "Publicité",
"photo":"blabla.jpg"
},
{
"titre": "Events",
"photo":"blabla.jpg"
}
]
}
Here is my Code:
- (void) viewDidLoad
{
[super viewDidLoad];
dispatch_async (kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
[self performSelectorOnMainThread:@selector(fetchedData:)withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsvideo = [json objectForKey:@"titre"];
NSLog(@"Album: %@", albumsvideo);
}
Log returns null
.
Upvotes: 1
Views: 3792
Reputation: 1
For all the bigginers out there. this will help you
synch.m
========
#import "thenewapi.h"
@interface thenewapi ()
{
NSData *data;
NSMutableArray*mutarray;
int index;
NSString *s;
NSMutableArray *arr;
NSMutableArray *imgarr;
}
@end
@implementation thenewapi
- (void)viewDidLoad {
[super viewDidLoad];
index=0;
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ir.com/wecare/api/partnership/partnership_heading?format=json"]];
NSURLResponse *response=nil;
NSError *error=nil;
data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
mutarray=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
arr=[mutarray valueForKey:@"0"];
_idlbl.text=[arr valueForKey:@"id"];
_titlelbl.text=[arr valueForKey:@"title"];
_destxtvw.text=[arr valueForKey:@"description"];
imgarr=[mutarray valueForKey:@"images"];
s=[[imgarr objectAtIndex:index] valueForKey:@"image"];
NSString *f=[NSString stringWithFormat:@"http://irtech.com/wecare/uploads/partnership/%@",s];
NSURL *g=[[NSURL alloc]initWithString:f];
data=[NSMutableData dataWithContentsOfURL:g];
self.imgvw.image=[UIImage imageWithData:data];
// Do any additional setup after loading the view.
}
- (IBAction)clickbtn:(id)sender
{
++index;
s=[[imgarr objectAtIndex:index]valueForKey:@"image"];
NSString *f=[NSString stringWithFormat:@"http://irdtech.com/wecare/uploads/partnership/%@",s];
NSURL *g=[[NSURL alloc]initWithString:f];
data=[NSMutableData dataWithContentsOfURL:g];
self.imgvw.image=[UIImage imageWithData:data];
}
========================================================================================================
Asynch.h
========
#import <UIKit/UIKit.h>
@interface thenewAsynch : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *imgvw;
@property (strong, nonatomic) IBOutlet UITableView *tbl;
@property (strong, nonatomic) IBOutlet UIButton *click;
@end
Asynch.m
========
#import "thenewAsynch.h"
@interface thenewAsynch ()
{
NSDictionary *dic;
NSMutableArray *mutarray;
NSMutableData *mutdata;
NSString *s;
NSArray *arr;
NSArray *imgarr;
NSData *data;
int index;
}
@end
@implementation thenewAsynch
- (void)viewDidLoad {
[super viewDidLoad];
mutarray=[[NSMutableArray alloc]init];
mutdata=[[NSMutableData alloc]init];
dic=[[NSDictionary alloc]init];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://irtech.com/wecare/api/partnership/partnership_heading?format=json"]];
NSURLConnection *connect=[NSURLConnection connectionWithRequest:request delegate:self];
NSLog(@"Connection String=%@",connect);
[self.view addSubview:_tbl];
arr=[mutarray valueForKey:@"0"];
imgarr=[mutarray valueForKey:@"images"];
// Do any additional setup after loading the view.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellid=@"Cell Identifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
if(cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
if(indexPath.row==0)
{
cell.textLabel.text=[arr valueForKey:@"id"];
}
else if (indexPath.row==1)
{
cell.textLabel.text=[arr valueForKey:@"title"];
}
else if (indexPath.row==2)
{
cell.textLabel.text=[arr valueForKey:@"subtitle"];
}
else if (indexPath.row==3)
{
cell.textLabel.text=[arr valueForKey:@"description"];
}
return cell;
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
// return mutarray.count;
//}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
mutarray=[NSJSONSerialization JSONObjectWithData:mutdata options:NSJSONReadingMutableContainers error:nil];
arr=[mutarray valueForKey:@"0"];
imgarr=[mutarray valueForKey:@"images"];
s=[[imgarr objectAtIndex:index]valueForKey:@"image"];
NSString *f=[NSString stringWithFormat:@"http://irtech.com/wecare/uploads/partnership/%@",s];
NSURL *g=[[NSURL alloc]initWithString:f];
data=[NSMutableData dataWithContentsOfURL:g];
self.imgvw.image=[UIImage imageWithData:data];
[_tbl reloadData];
}
- (IBAction)clickclick:(id)sender
{ ++index;
s=[[imgarr objectAtIndex:index]valueForKey:@"image"];
NSString *f=[NSString stringWithFormat:@"http://irtech.com/wecare/uploads/partnership/%@",s];
NSURL *g=[[NSURL alloc]initWithString:f];
data=[NSMutableData dataWithContentsOfURL:g];
self.imgvw.image=[UIImage imageWithData:data];
}
Upvotes: -2
Reputation: 27225
You are doing it wrong. You have filled your JSON Data in your Dictionary (named json
) correctly. But then you have an Array of Dictionaries
(called Albumvideo
) inside your Main Dictionary
and value of titre
is inside Albumvideo
Array.
The Correct Code is :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsvideo = [json objectForKey:@"Albumvideo"];
NSString *titre1 = [[albumsvideo objectAtIndex:0]valueForKey:@"titre"];
NSString *titre2 = [[albumsvideo objectAtIndex:1]valueForKey:@"titre"];
Understand the Concept. It depends on what you have inside your JSON
. If it's an Array ( Values inside [ ]
) then you have to save in NSArray
, if it's a Dictionary ( Values inside { }
) then save as NSDictionary
and if you have single values like string , integer, double then you have to save them using appropriate Objective-C Data types.
Hope, you got some proper idea about JSON Parsing.
Upvotes: 13
Reputation: 8320
Answered by Vin is right. Basically, to parse json response look at the kind of bracket used.
Start parsing with the outer symbol and check for the symbol. If it is,
1) {
then it is NSDictionary.
2) [
then it is NSArray.
These simple rules will make your life easy. :)
Upvotes: 1