Skip to main content

How to Pars JSON in iOS - Objective C

JSON Pars




Objective

This is a quick guide on JSON Parse in iOS. A simple example described how to parse JSON and store JSON data in array or dictionary for further use.
Introduction:
JSON stands for JavaScript Object Notation. It is data interchange format that can be easily read and write by human and can be easily parse by machine. Given steps are very simple and it explain in simple manner with suitable code, to understand parse JSON in iOS we need to follows given steps.

Step 1 Create XCode Project

Create new XCode project name it as JSONParsingDemo. It contains one UIViewController in Main.storyboard file. The UIViewController class provides the fundamental view-management model for all iOS apps.

Step 2 Parse JSON File

The given code describe how to convert json file into NSData. Then pass that data object in NSJSONSerialization method JSONObjectWithData:options:error. That will return array or dictionary as per JSON format.
The NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

-(void)parseJSONFile
{
       NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Displaydata" ofType:@"json"]]; 

       NSDictionary *dictTemp = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
      NSArray *arrColors = [dictTemp valueForKey:@"colorsArray"];

      for (inti=0; i< arrColors.count; i++)  { 

           Colors *colors = [[Colors alloc] init];
           [colorsparseResponse:[arrColors objectAtIndex:i]];
           [marrAllColorsaddObject:colors];
     }
  [self displayAllColros];
}


Step 3 Create Colors Model File

Create a model class that is subclass of NSObject class. That contains all the property with the keys available in JSON dictionary and write a parse JSON dictionary method and store it in class property.
In our example we have created Colors class as below.
Colors.h
#import<Foundation/Foundation.h>
@interface Colors : NSObject
@property (nonatomic,strong) NSString *colorName;
@property (nonatomic,strong) NSString *hexValue;
- (int)parseResponse:(NSDictionary *)receivedObjects;
@end

Colors.m:
#import "Colors.h"
@implementation Colors
@synthesizecolorName;
@synthesizehexValue;
- (int)parseResponse:(NSDictionary *)receivedObjects
  {
     colorName = [receivedObjects objectForKey:@"colorName"];
     hexValue = [receivedObjects objectForKey:@"hexValue"];
     return 0;
  }
@end

Step 4 Display Colors Function

In our this example it contains array of colors with key colorsArray. Create color object and call parseResponse method and pass dictionary which contains color name and its hex value. Add color object in a mutable array.
Now you can use color object and its color name and hex value property in whole class. To describe how to access color object’s property I have print color name and hex value in displayAllColors method.

-(void)displayAllColors 
 { 
      for (int i=0; i < marrAllColors.count ; i++)  { 

          Colors *color = [marrAllColors objectAtIndex:i]; 
         NSLog(@"Color : Name = %@ hexValue = %@",color.colorName,color.hexValue); 
     } 
 } 


Step 5 Call Function from viewDidLoad



Call parseJSONFile method from viewDidLoad() which looks like.

-(void)viewDidLoad 
  { 
     [super viewDidLoad]; 
     marrAllColors = [[NSMutableArray alloc] init]; 
     [self parseJSONFile]; 
  } 

I hope you found this blog helpful while JSON Parse in iOS. 
                      Free Download Full Source Code!!!

Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...