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

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...