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