Swift 4调用Walmart API解析JSON数据报错,求问题原因排查
Hey there! Let’s dig into that persistent JSON parsing error you’re hitting while working with the Walmart API in Swift 4. I know how frustrating it is when tutorials don’t cover the exact kink you’re stuck on, so let’s break this down.
First off, the JSON snippet you shared cuts off at "format": "j...—we’ll need the full, valid JSON response from the API to spot structural mismatches. Also, sharing the exact error message from your console (like "keyNotFound" or "typeMismatch") and your current Swift parsing code (especially your Codable models and decoding logic) will help zero in on the issue fast.
That said, here are the most common pitfalls that trip up Swift 4 developers working with the Walmart API:
1. Mismatched Model Structure
Walmart’s API responses are nested—usually, product data lives inside an items array under a top-level object. If you’re trying to decode a product model directly instead of wrapping it in a parent struct that matches the API’s top-level keys, you’ll get a parsing failure.
For example, if the full API response looks like this:
{ "query": "ipod", "sort": "relevance", "format": "json", "items": [ { "name": "Apple iPod Touch (7th Gen)", "salePrice": 199.99, "productId": 876543 } ] }
Your Swift models need to mirror this structure:
// Top-level response struct to match the API's root keys struct WalmartSearchResponse: Codable { let query: String let sort: String let format: String let items: [Product] } // Product struct for individual item data struct Product: Codable { let name: String let salePrice: Double let productId: Int }
2. Data Type Mismatches
Walmart’s API sometimes returns values in unexpected formats:
- Prices might come as strings with currency symbols (like
"$199.99") instead of raw numbers—if your model usesDouble, this will fail. You’ll need to clean the string first or use a custom decoder. - Optional fields: Some product attributes might be
nullin the JSON. If your model declares those properties as non-optional (no?), decoding will crash. Always mark potentially missing fields as optional (e.g.,let brand: String?).
3. Key-Name Mismatches
If your Swift model’s property names don’t exactly match the JSON keys (e.g., JSON uses itemName but your model uses productName), you need to map them using CodingKeys:
struct Product: Codable { let productName: String let price: Double enum CodingKeys: String, CodingKey { case productName = "name" case price = "salePrice" } }
4. Encoding or Request Issues
- Make sure your API request includes the correct
Accept: application/jsonheader—sometimes the API returns HTML error pages instead of JSON if headers are wrong. - When decoding, confirm you’re using
.utf8encoding for the data and print the full error (not just the localized description) for better debugging:
do { let decoder = JSONDecoder() let response = try decoder.decode(WalmartSearchResponse.self, from: data) // Process your products here } catch { print("Parsing failed: \(error)") }
Once you share the full JSON response, exact error message, and your code, we can pinpoint the exact issue.
内容的提问来源于stack exchange,提问作者user8474913

