Swift 5:给定的数据不是有效的JSON(将数据从API加载到表格视图)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 5:给定的数据不是有效的JSON(将数据从API加载到表格视图)相关的知识,希望对你有一定的参考价值。

我正在尝试从API获取一些数据。当我将函数连接到IBAction时,它可以很好地获取数据,但是当我在viewDidLoad()作为常规函数执行它时,它将无法正常工作。

我希望在应用程序加载时生成它,以便我可以将它们显示到表格视图中,而不必每次都单击按钮来加载它。

尝试从viewDidLoad()执行函数后,出现“给定数据无效的JSON错误”

下面是参考代码:

struct Claims: Decodable {
    let id: Int
    let submission_date: String
    let status: String
    init(json: [String:Any]) {
        id = json["id"] as? Int ?? -1
        submission_date = json["submission_date"] as? String ?? ""
        status = json["status"] as? String ?? ""
    }
}

class DashboardController: UIViewController, GIDSignInUIDelegate {

    var claimSummaryArray: [ClaimProperties] = []
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    override func viewDidLoad() {
        getData()
    }

    func getData() {
        guard let urlString = URL(string: "https://claim.ademo.work/claims/") else { return }
        var requestAPI = URLRequest(url: urlString)

        requestAPI.httpMethod = "GET"
        requestAPI.addValue("application/json", forHTTPHeaderField: "Content-Type")
        requestAPI.addValue("application/json", forHTTPHeaderField: "Accept")
        requestAPI.setValue("Bearer (appDelegate.userAppToken)", forHTTPHeaderField: "Authorization")

        let task = URLSession.shared.dataTask(with: requestAPI) { (data, response, error) in
            if let data = data {
                do {
                    let json = try JSONDecoder().decode([Claims].self, from: data)
                    print (json)
                } catch let error {
                    print("Seems to have an error: (error)")
                }
            }
        }
        task.resume()
    }
}

返回的数据变量(通过IBAction /单击按钮执行):

[ClaimApp.Claims(id: 1, submission_date: "2020-02-28T13:50:41.000+08:00", status: "pending"), ClaimApp.Claims(id: 2, submission_date: "2020-02-28T13:53:38.000+08:00", status: "pending"), ClaimApp.Claims(id: 3, submission_date: "2020-02-28T14:21:46.000+08:00", status: "pending"), ClaimApp.Claims(id: 4, submission_date: "2020-02-28T14:22:07.000+08:00", status: "pending")]

返回的错误(通过从viewDidLoad()调用普通函数执行:]

Seems to have an error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

PS /我是新来的,如果有任何误会或困惑,我们深表歉意。

答案

请在viewDidLoad中检查是否在下面的行中获取了[[userAppToken的值

requestAPI.setValue("Bearer (userAppToken)", forHTTPHeaderField: "Authorization")

以上是关于Swift 5:给定的数据不是有效的JSON(将数据从API加载到表格视图)的主要内容,如果未能解决你的问题,请参考以下文章

给定的数据不是有效的 JSON

如何检查给定字符串是不是是Java中的有效JSON

如何从 JSON 文件构建模型

无法在swift 3中解析Json?

Swift - JSONSerialization 无效的 JSON

Swift - JSONSerialization 无效的 JSON