求助:JSONDecoder无法解析数据,调用URL接口始终返回JSON错误
Hey there! Let's dig into why you're hitting that JSON parsing error even when your setup looks right. I've run into this exact issue a few times, so here are the most common culprits to check:
This is the #1 reason for parsing failures—even tiny discrepancies break everything:
- Case sensitivity: If the JSON uses
userNamebut yourTopstruct hasusername, the decoder will throw an error. Double-check every field name's case. - Type mismatches: If the JSON returns a numeric value (like
"count": 10) but your struct useslet count: String, parsing will fail immediately. Match types exactly. - Missing optional markers: If a JSON field is optional (might not exist in some responses), mark the struct property with
?. For example:let description: String?instead oflet description: String.
Example of a matching pair:
JSON:
{ "articleTitle": "Swift Parsing Tips", "viewCount": 420 }
Struct:
struct Top: Codable { let articleTitle: String let viewCount: Int }
- Make sure your
Topstruct explicitly conforms toCodable(orDecodableif you only need to parse data). It's easy to forget this line! - If you need to map JSON field names to different struct property names, you must define a
CodingKeysenum. For example:struct Top: Codable { let productName: String enum CodingKeys: String, CodingKey { case productName = "item_name" // Maps JSON's "item_name" to struct's productName } }
Sometimes the API returns something different than you expect:
- Array vs. Single Object: If you're trying to decode a single
Topobject but the API returns an array ([Top]), usingJSONDecoder().decode(Top.self, from: data)will throw an error. Switch to decoding[Top].selfinstead. - Hidden Format Issues: Print the raw response data as a string to verify what you're actually receiving:
This often reveals hidden issues like extra commas, unclosed quotes, or nested data you didn't account for.if let rawJson = String(data: responseData, encoding: .utf8) { print("Raw JSON response: \(rawJson)") }
If your target Top data is wrapped inside a parent object (common in API responses), you need a wrapper struct to decode it properly. For example:
JSON:
{ "data": { "title": "Sample Post", "likes": 15 } }
Wrapper struct:
struct TopResponse: Codable { let data: Top } struct Top: Codable { let title: String let likes: Int }
Then decode using TopResponse.self instead of Top.self.
Some APIs return JSON data but label the response as text/plain instead of application/json. While JSONDecoder usually handles this, it's worth checking the response headers to confirm. If needed, you can still force-decode the data regardless of the header.
Start with printing the raw JSON—this will almost always point you to the root issue. Once you confirm the actual structure, matching it to your Top struct should fix the error.
内容的提问来源于stack exchange,提问作者Pegasus

