Transforming JSON into model objects in your apps just became a whole lot easier with the introduction of Decodable in Swift 4. In today’s lesson, I want to walk through the old way of using JSONSerialization and then show you the new JSONDecoder method. We can retire a bunch of JSON serializer pods now that we have this feature natively supported.
URLs for JSON blobs:
https://api.letsbuildthatapp.com/jsondecodable/course
https://api.letsbuildthatapp.com/jsondecodable/courses
https://api.letsbuildthatapp.com/jsondecodable/website_description
https://api.letsbuildthatapp.com/jsondecodable/courses_missing_fields
Completed Source Code
https://www.letsbuildthatapp.com/course_video?id=1562
Instagram Firebase Course
https://www.letsbuildthatapp.com/course/instagram-firebase
Facebook Group
https://www.facebook.com/groups/1240636442694543/
iOS Basic Training Course
https://www.letsbuildthatapp.com/basic-training
Follow me on Twitter: https://twitter.com/buildthatapp
Amazon Auto Links: No products found.
thank you. it was really helpful.
Decoder Not working for Date field ? awesome video can u help
How do you display the called information in a label on the storyboard?
Great tutorial, thank you…
Hey Brian!
Thank for this tutorial, before watching this video I was writing code like it is 2015. Thank to you I got update.
While trying different JSON to parse with this method I came across a Complex JSON (find JSON here – https://bpaste.net/show/9bed8b035d24 ) which I’m not able to parse using Decodable protocol. Brian can you please help me with that?
Thanks in advance.
the statement guard let data = data is really killing me
Thank you bro for the video
Hello, I just want to ask..Should I user more libraries in the project or create native custom code..For ex: Fetching response from API should I use alamofire or normal native code like URLSession ?
Thanks brother its awesome. 🙂
Im placing all the data in a table view but getting the following error
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: “Expected to decode Array but found a dictionary instead.
Any chance you could tell me what my code needs? Please see below:
@objc func fetchJSON() {
let urlString = “https://newsapi.org/v2/top-headlines?sources=news-com-au&apiKey=46dcfb1d69214f0b937b0f9871b7a257”
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) {(data, _, err) in
DispatchQueue.main.async {
if let err = err {
print(“Failed to get data from URL:”, err)
return
}
guard let data = data else {return}
do {
let decoder = JSONDecoder()
self.articles = try decoder.decode([Article].self, from: data)
self.tableView.reloadData()
} catch let jsonErr {
print(“Failed to decode:”, jsonErr)
}
}
}.resume()
refresher.endRefreshing()
}
Thank you. this video tutorial. It’s worked. 🙂
one of the best tutorial for API’s , thanks man
Super video! Thx!
You’re just a magician
fuck i hate this language, im going to hang myself
I’m new to Swift and have spent hours trying to parse an array of object in JSON. Thank you sooooooo much!
How can i deserialize token?
how to parson json .post method in swagger client
is it still worth using Alamofire? and how do you use JSONDecodable with Alamofire? I have found this https://grokswift.com/decodable-with-alamofire-4/
Thank you so much, you saved my day
Help be print the courses or simply help me print data in the array course
Hi, thank you so much for this video, it helped a lot for my final project, but I still have one problem, I need to place data on a variable but since the network call is async, my variable return empty and before the call is over, how can I fix this
so what about additional variables ? Could you video about additional variables ?
Hi Brian, I need your help with something, is there a way to email you my issue?
How can i deserialize token?
Great video thank you for sharing
Thank you for your classes. I am getting an error “The data couldn’t be read because it isn’t in the correct format.” while using single line Json parsing. Is there any possibility to find, which key raising this error.
Awesome!
Hi. Great tutorial!!! I only have one problem, I have a web service and the data that it returns is OK (I use Postman to test it and in Android Studio is OK too), but in Xcode some fields returns as “nil” and I do not know why.
As a developer with big experience, can you tell how frequent is there a need for you to use CocoaPods ? I mean just generally speaking, do you use 3rd party libraries in all your projects ?
Great video, Really helps me lot…….
Best, most helpful video out there.. thank you so much. I subscribed.
Very nice tutorial sir. JSON parsing is really very easy now. But I have one question. How can we add some default value to the optional property? Do we need to write any code inside the class/structure/enum definition..??
am not able to access the value form websiteDescription.courses. can you please help me
Nice, simple and easily understandable tutorial ! keep going bro
This tutorial really helpful for me thanks:)
hey man, awseome tutorial but i have an error that occerps when i’m traying to parse some big array of json, could you help plz?
Here’s code and i’m trying to receive the ids of all photos from picsum
let jsonUrl = “https://picsum.photos/list”
guard let url = URL(string: jsonUrl) else { return }
URLSession.shared.dataTask(with: url) { (data, responce, err) in
guard let data = data else { return }
do {
let listMine = try JSONDecoder().decode([List].self, from: data)
print(listMine)
} catch let jsonErr {
print(jsonErr.localizedDescription)
}
}.resume()
great thanks a lot ! 🙂
Excuse me sir, How could I handle some null value in the array JSON.
For example
[
{
id : 1 ,
name : ABCD,
location[13.22222 , 101.22222]
}
{
id : 2,
name : CDEF,
location [ null , null ]
}
{
id : 3 ,
name : HHHH,
location[14.2342 , 101.23222]
}
]
And this is my script to get data
func getAllLocationDataToStorage(dataJSON : JSON){]
let count = dataJSON.count
locationStorages = []
for index in 0..
{
if (jsonArray[0][“locations”]) != nil {
let vehicleLocation = jsonArray[0][“locations”] as! NSArray
storage.latitude = vehicleLocation[0] as! Double
storage.longitude = vehicleLocation[1] as! Double
}
locationStorages.append(storage)
}
else{
print(“bad json”)
}
}catch let error as NSError{
print(“Error JSON Serialization : ” , error)
}
}
}
And I got error when some null
Could not cast value of type ‘NSNull’ (0x11322f850) to ‘NSNumber’ (0x111c42b40).
2018-09-17 13:10:48.101714+0700 DGFTrackingIOSProject[6702:779736] Could not cast value of type ‘NSNull’ (0x11322f850) to ‘NSNumber’ (0x111c42b40).
(lldb)
How would you do it if you have a paged API and JSON data? The API I’m working with I can get all the data from the first page, but not the other pages.
Great video sir your all videos are very helpfull thank you
Hello, I need to download a dpf from a url … it is a specific pdf that is posted on a web site … I can show it in a webview but not download it on the phone … do you have any idea how to do it? I’m searching the internet but I can not find something specific …
{
“date”: “9-07-2018”,
“data”: {
“total”: 1150,
“day_items”: [
{
“amount”: 55,
“category”: “Gift”,
“colorcode”: “#ba68c8”,
“contents”: “Keychain from Archies”,
“id”: “hash of data”,
“payment_method”: “card”,
“receipt_url”: “url”,
“time”: 1529489815566
},
I want to know how to decode “data” in this above JSON in
let dayEvent = try JSONDecoder().decode(Decodable.Protocol, from: data)
I don’t get how this works in some case..I can use AFNEtworking with something like this `apiRequest(withMethod: “GET”, toPath: nil, atEndpoint: realURL, withJSON: nil, success: { (operation, JSON) in ….. and get data back if I build the URL myself…but when I use the URLSession.shared.dataTask and do the same thing and build the URL myself..I am getting a 401 unauthorized on my response. Mind you the URLs that are being created are the exact same. is the URLSession.shared.dataTask not doing a ‘get’ request? What am I missing here. I really want to be able to use the newer style vs the old style
Thanks so much!!! Took me no time at all to get the job done!
Thank you for this video Brian! I was wondering how can I update a UILabel to print out “websiteDescription.name”. Thanks for the help.