You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift4 JSONDecoder报错:期望解析字典却得到数组求助

Fixing "Expected to decode Dictionary<String, Any> but found an array instead" in Swift JSONDecoder

Hey there! Let's break down this common JSON decoding issue you're hitting. The error message is spelling out exactly what's wrong: your code is trying to decode the server's response as a single dictionary (like {"email": "test@example.com", "password": "test"}), but the server is actually sending back a JSON array (like [{"email": "test@example.com", "password": "test"}]).

Step 1: Verify the Server's Response Format

First, let's confirm what the server is actually sending. Add this code inside your dataTask completion handler to print the raw response string—this will let you see the exact structure you're working with:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")
        return
    }
    
    // Print raw JSON string to check its structure
    if let responseString = String(data: data, encoding: .utf8) {
        print("Server Response: \(responseString)")
    }
    
    // Your existing decoding code goes here
}
task.resume()

If the output starts with [ and ends with ], that confirms you're getting an array instead of a single dictionary.

Step 2: Adjust Your Decoding Logic

Assuming the server returns an array (even if it's just one matching user), you need to decode it as an array of your model type instead of a single instance.

First, create a Codable model that matches the fields in your JSON response:

struct User: Codable {
    let email: String
    let password: String
    // Add any other fields from your MySQL query, like userID or username
}

Then update your decoding code to target an array:

do {
    // Decode as [User] instead of User.self
    let users = try JSONDecoder().decode([User].self, from: data)
    
    // If you expect only one matching user (for login), grab the first element
    if let loggedInUser = users.first {
        print("Successfully decoded user: \(loggedInUser.email)")
        // Proceed with your login flow here
    } else {
        print("No user found with the provided credentials")
    }
} catch {
    print("Decoding error: \(error)")
}

Step 3: Double-Check Your PHP Backend

It's also worth a quick check of your PHP script. If you're using json_encode($result) where $result is the raw output from a MySQL query, that will return an array of rows—hence the JSON array. If you only ever expect one row, you could modify the PHP to return just the first row as a dictionary, but adjusting your Swift code to handle arrays is more flexible (in case you need to return multiple rows later).

That should fix the decoding error! Let me know if you run into any other snags with your login flow.

内容的提问来源于stack exchange,提问作者A Bowl of Fruit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:01:53