JSON Parsing in Objective-C

objective c json encoder
data to json objective-c
objective-c read json file
how to create json object in objective-c
objective-c get json from url
how to parse json array in objective-c
sbjson objective-c
objective-c convert json string to array

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.

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.

How To Fetch and Parse JSON Data, Fetching JSON Data Using Meetup API. First create a new file using Objective-C protocol template and name it as MeetupCommunicatorDelegate  SBJson 5. Chunk-based JSON parsing and generation in Objective-C. Overview. SBJson's number one feature is stream/chunk-based operation. Feed the parser one or more chunks of UTF8-encoded data and it will call a block you provide with each root-level document or array.

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. :)

Basic JSON parsing in iOS, If something goes wrong, the API method will create an NSError object and update the pointer accordingly. Objective-C. Different different examples of JSON parsing using Objective-C and Swift Language json json-api json-parsing ios swift-language swift5 objective-c codable nsurlrequest alamofire swiftyjson

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];



}

Objective-C Language, Objective-C Language JSON Parsing using NSJSONSerialization Objective c. Example#. NSError *e = nil; NSString *jsonString = @"[{  Objective-C's class libraries define the NSJSONSerialization class, which can serialize to and from JSON. It converts JSON to NSDictionary objects of values, with the keys, the names of the slots in the JSON, and the values of their JSON. It's available in iOS 5.0 and later.

iOS QuickTip: Getting and Reading JSON Data from a URL , Retrieving and Reading the JSON via Objective-C. Now you'll want to head back into your iOS project since this is where you want to get this  Basic JSON parsing in iOS by Jason Shapiro | Sep 2, 2013 While there are many 3rd party APIs available to help simplify working with JSON in the context of other tools (such as Core Data and RESTful WebServices), this article focuses on how one can use the “out of the box” support included in the Foundation framework.

Parse JSON with Objective-C. · GitHub, Parse JSON with Objective-C. gistfile1.m. NSError *error = nil;. id jsonObject = [​NSJSONSerialization. JSONObjectWithData:[string  Unfortunately, Objective-C doesn’t treat functions as first class citizens in the language (and therefore, it isn’t idiomatic to compose functions). Object-oriented programming can still represent partial functions, but with more boilerplate.

johnezang/JSONKit: Objective-C JSON, Parsing / deserializing will automagically decompress a buffer if it detects a gzip signature header. You can compress / gzip the serialized JSON by passing  In such cases, the way that data is expressed may vary, but usually is preferred either the JSON or the XML format. iOS SDK provides classes for handling both of them. For managing JSON data, there is the NSJSONSerialization class. This one allows to easily convert a JSON data into a Foundation object (NSArray, NSDictionary), and the other way

Comments
  • try logging the error: NSLog(@"Error: %@", [error localizedDescription])
  • @nic Please include your JSON in the question itself. Questions are supposed to be self-contained and links tend to stop working after a while.
  • The json is in in the question!
  • Did you make sure responseData is not nil or at least what you expect to get back from the server?
  • @bl it wasn't at the time.
  • +1. Excellent explanation, and it's entirely correct (unlike the others)
  • Sound's great :-) Is it the same process if I have array inside other array (in my JSON)? I've made this for my "titre" : NSArray *titre = [albumsvideo valueForKey:@"titre"];
  • @NicolasWilhem : Understand the Concept. It depends on what you have inside your JSON. If it's an Array then you have to save in NSArray, if it's a Dictionary 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.
  • Thank you guys, with you I learned faster and better than reading tons of incomplete tutorial. I now have a good starting point.
  • @NicolasWilhem: Don't Edit the Question. You should ask a new One.