Parsing JSON from URL ends up with an Error - Swift 5
Here is how to decode all the json data into a swift struct:
import Foundation
struct Stations: Codable {
let company: [String]
let href: String
let id: String
let location: LocationJson
let name: String
let stations: [Station]
}
struct Station: Codable {
let empty_slots: Int
let extra: Extra
let free_bikes: Int
let id: String
let latitude: Double
let longitude: Double
let name: String
let timestamp: String
}
struct ResponseJSON: Codable {
let network: Stations
}
struct LocationJson: Codable {
let city: String
let country: String
let latitude: Double
let longitude: Double
}
struct Extra: Codable {
let slots: Int
let status: String
let uid: String
}
func getBikeData(){
guard let url = URL(
string: "https://api.citybik.es//v2/networks/baksi-bisim"
) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data, error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
print(jsonResponse) //Response result
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
//Decode JSON Response Data
let model = try decoder.decode(
ResponseJSON.self, from: dataResponse
)
print(model) //Output - 1221
} catch let parsingError {
print("Error", parsingError)
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
getBikeData()
Swift 5 Json parsing error dataCorrupted
// problem in response type and encoding. It should be application/json and //unicode but actually it is:
//response content-type: text/plain; charset=ISO-8859-1
struct Facts:Codable {
let title: String
let rows: [Rows]!
}
struct Rows:Codable {
var title: String?
var description: String?
var imageHref: String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
guard let url = URL(string: jsonUrlString) else{return}
// var request = URLRequest(url: url)
// request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
// request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
guard let string = String(data: data, encoding: String.Encoding.isoLatin1) else { return }
guard let properData = string.data(using: .utf8, allowLossyConversion: true) else { return }
do{
let facts = try JSONDecoder().decode(Facts.self, from: properData)
//dump(facts)
print(facts.title)
for row in facts.rows {
print(row.title ?? "no title")
print(row.description ?? "no description")
print(row.imageHref ?? "no img url")
print("---")
}
} catch let error {
print(error)
}
}.resume()
}
}
swift Parsing JSON from URL
I cleaned things up a bit, drop the NS stuff and protected results with guard
.
let url = URL(string: "http://localhost.192.168.1.40.xip.io:8888/store1.php")!
URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data else { return }
guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { return }
guard let jsonObj = json as? [String: Any] else { return }
guard let telefon = jsonObj["telefon"] as? String else { return }
print(telefon)
}
A bit more debugging.
let url = URL(string: "http://localhost.192.168.1.40.xip.io:8888/store1.php")!
URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data, !data.isEmpty else {
print("Error: data is nil or empty")
return
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else {
print("Error: data contains no JSON")
return
}
guard let jsonObj = json as? [String: Any] else {
print("Error: JSON is not a dictionary")
return
}
guard let telefon = jsonObj["telefon"] as? String else {
print("Error: Object has no 'telefon' key")
return
}
print(telefon)
}
Trying to parse Json data into model Class this getting error while using codable
As error says: let error: String?
error property is expected to be a String
type - but server returns a Dictionary
there.
The JSON you posted seems to have null
there, but probably error is shown due to different JSON data - one that has error
object.
Gets error when getting data from API in Swift: Expected to decode DictionaryString, Any but found an array instead.
The JSON data contains a list of fruits (an array), but you try to decode a FruitsData
. It would expect the JSON top-level to look like this:
{
"fruits": [ … ]
}
Instead, you need to decode an array of fruits directly like this:
var fruits:[Fruit]?
do {
fruits = try JSONDecoder().decode([Fruit].self, from: data)
}
catch {
print(String(describing: error))
}
Related Topics
Kvo Listener Issues in Swift 4
My UIcollectionview Does Not Scroll Smoothly Using Swift
Switch Statement Where Value Is Int But Case Can Contain Array
Do Not Copy Swift Libraries with Xcode 8
Swift 4: How to Asynchronously Use Urlsessiondatatask But Have The Requests Be in a Timed Queue
Swift Loaditem Closure Not Running
How to Call Https Url in UIwebview (Swift)
Editable Nstextview from Interface Builder
Uibutton Background Color Overlaps Text on Highlight
Swift Sha256 Encryption Returns Different Encrypted String Compare to Objective C
Reload Tableview After Clicking The Button Present Inside One of The Tableview Cell in Swift
How to Convert an Array to List in Realm
Realm Write Transaction Failing, Despite Being in Transaction
Cannot Use Mutating Member ... Because Append