How to decode json in Swift IOS app part 1 (simple json)

what is json ?


JSON: JavaScript Object Notation.

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.


it is used to exchange data between server and your app as a developer you have to know about what is json. how is data formatted in json because most of the rest api return data in json format .

how json look likes ?

this is json it returns data in dictionary, we also called as in a key value pair



let json = """
{
 "name": "madhav",
 "location": "noida, MA",
 "class": 3,
 "height": 2.5,
  college : "noida "
}""".data(using: .utf8)!


lets decode this json and use in our app

there is many way to decode json in swift but most of the famous method in ios to use a decodable , encodable, codable protocol


first we have to create a json object using structure and this to be inherited from a codable protocol



struct Me : Codable {
var name:  String
var location: String
var class : Int
var height: Float
var college : String
}

most important point you have to remember that the variable name in your structures should be exactly match with your json.


Now decode the json using json Decoder



let decoder = JSONDecoder()
do {
 let myself = try decoder.decode(Me.self, from: json)
 print(myself)
 print(myself.name)
 print(myself.location)
 print(myself.class)
 print(myself.height)
 print(myself.college)
} catch {
 print(error)
}

output -

print(myself)

Me(name: "madhav", location: "noida , MA", class: 3, height: 2.5, college : noida)

print(myself.name) print(myself.location) print(myself.class) print(myself.height) print(myself.college)

madhav  noida  3 2.5 noida


9 views0 comments

Recent Posts

See All

How to create a Web View In swift Ios

import UIKit // import webkit framework import WebKit class ViewController: UIViewController, WKNavigationDelegate { // view controller inherit from WkNavigation Delegate // create a object of Wk

How to work with an api in Swift

Create a URl let url = URL(string: " your_url")! Create a URL Session let datatask = URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data { print(data) }else { p

 

Follow

  • Facebook
  • Instagram
  • LinkedIn
  • Twitter

Contact

Address

VILLAGE-HiRAPUR KALAN
POST-KARANWAS DIBAI

©2020 by ThE RoYaL LaKsHyA.