簡體   English   中英

在Swift 4中使用新的JSONDecoder協議時,我得到“無法讀取數據,因為數據格式不正確。” 錯誤

[英]When using the new JSONDecoder protocol in Swift 4 i'm getting the 'the data couldn’t be read because it isn’t in the correct format.' error

Kinda是swift的新功能,尚未使用swift 4解決此錯誤的解決方案。

使用JSONDecoder函數時,出現一個錯誤,提示“由於格式不正確,無法讀取數據。” 我已經通過驗證器運行了JSON,它說那里一切都很好,所以我只是不明白為什么會發生此錯誤

我的解碼代碼如下:

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()
    }
}

在JSON中,我已將其轉換為UTF8,所以我認為這不是錯誤的出處

我在另一個看起來像這樣的文件中有這個結構:

    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
    }
}

在這件事上的任何和所有幫助將不勝感激!

確保將日期格式轉換為TimeIntervals或String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM