Kinda New to swift and haven't seen a solution for this error using swift 4.
When using the JSONDecoder function I've been getting an error saying that 'the data couldn't be read because it isn't in the correct format.' I've run my JSON through a validator and it's saying everything is ok there so I'm just not understanding why this error is happening
my code for decoding is as follows:
import UIKit
class inputscreen: UIViewController {
// the JSONData.php is where the data is being converted into JSON using PhP
final let url = URL(string: "JSONData.php")
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func downloadJson() {
guard let downloadURL = url else {return }
URLSession.shared.dataTask(with: downloadURL) {data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something went wrong")
return
}
// print(data)
print("downloaded")
do {
// this is where the error is happening, everything else is getting through my checks.
let decoder = JSONDecoder()
let variables = try decoder.decode(Variables.self, from:data)
print(variables.variables[0].TblStaffID)
print("success")
} catch {
print(error.localizedDescription)
}
}.resume()
}
}
in the JSON I've converted it to UTF8 so I don't think that's where the error is coming from
I have the struct for this in a different file which looks like this:
import Foundation
import UIKit
class Variables: Codable{
let variables: [Variable]
init(variables: [Variable]){
self.variables = variables
}
}
struct Variable: Codable {
let TblStaffID: Int
let User_code: String
let Title: String
let PreName: String
let Surname: String
init(TblStaffID: Int, User_code: String, Title: String, PreName: String, Surname: String){
self.TblStaffID = TblStaffID
self.User_code = User_code
self.Title = Title
self.PreName = PreName
self.Surname = Surname
}
}
any and all help on this matter would be appreciated!
确保将日期格式转换为TimeIntervals或String
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.