Swift开发:如何将接口返回的files JSON数据存入单个数组
Hey there! As a fellow Swift developer who’s been exactly where you are, let’s break this down step by step—getting that myFileArray you want is totally doable once you know the right tools to use.
First, Let’s Assume Your JSON Structure
Most API responses with a "files" array look something like this (tweak this to match your actual response):
{
"status": "success",
"files": [
{"name": "file1.pdf", "downloadUrl": "https://example.com/file1"},
{"name": "file2.jpg", "downloadUrl": "https://example.com/file2"}
]
}
Step 1: Define Codable Models
Swift’s Codable protocol is your go-to for JSON parsing. We’ll create two structs: one for a single file, and one for the full API response.
// Model for a single file (match the keys in your JSON exactly!) struct File: Codable { let name: String let downloadUrl: String // Add other fields from your JSON here (like file size, type, etc.) } // Model for the full API response struct ApiResponse: Codable { let files: [File] // Include other top-level JSON fields if you need them (like "status") }
Pro tip: If your JSON uses snake_case (e.g., download_url instead of downloadUrl), use CodingKeys to map the names correctly:
struct File: Codable { let name: String let downloadUrl: String enum CodingKeys: String, CodingKey { case name case downloadUrl = "download_url" } }
Step 2: Parse the JSON Data
Once you have the raw Data from your API call (via URLSession or your preferred networking library), decode it into your models:
func loadFiles(from apiData: Data) { do { // Decode the full API response let decodedResponse = try JSONDecoder().decode(ApiResponse.self, from: apiData) // Here's your desired array! let myFileArray = decodedResponse.files // Now you can use this array—print it, display in a table, etc. myFileArray.forEach { file in print("Found file: \(file.name) at \(file.downloadUrl)") } } catch { // Handle parsing errors (super helpful for debugging!) print("Oops, failed to parse JSON: \(error.localizedDescription)") print("Detailed error info: \(error)") } }
What If "files" Is Nested?
If your "files" array is tucked inside another object (e.g., under a "data" key), just adjust your response model to match:
struct ApiResponse: Codable { let data: DataContainer } struct DataContainer: Codable { let files: [File] }
Then access the array like decodedResponse.data.files.
That’s all there is to it! Once you get comfortable with Codable, JSON parsing becomes second nature. If you hit snags with your specific JSON structure, feel free to share more details and we can troubleshoot further.
内容的提问来源于stack exchange,提问作者Rishabh Shukla

