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

求助: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:

1. Mismatched Struct Properties & JSON Fields

This is the #1 reason for parsing failures—even tiny discrepancies break everything:

  • Case sensitivity: If the JSON uses userName but your Top struct has username, 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 uses let 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 of let description: String.

Example of a matching pair:
JSON:

{
  "articleTitle": "Swift Parsing Tips",
  "viewCount": 420
}

Struct:

struct Top: Codable {
    let articleTitle: String
    let viewCount: Int
}
2. Incorrect Codable Implementation
  • Make sure your Top struct explicitly conforms to Codable (or Decodable if 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 CodingKeys enum. 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
        }
    }
    
3. Unexpected JSON Structure

Sometimes the API returns something different than you expect:

  • Array vs. Single Object: If you're trying to decode a single Top object but the API returns an array ([Top]), using JSONDecoder().decode(Top.self, from: data) will throw an error. Switch to decoding [Top].self instead.
  • Hidden Format Issues: Print the raw response data as a string to verify what you're actually receiving:
    if let rawJson = String(data: responseData, encoding: .utf8) {
        print("Raw JSON response: \(rawJson)")
    }
    
    This often reveals hidden issues like extra commas, unclosed quotes, or nested data you didn't account for.
4. Nested JSON Data

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.

5. Unusual Content-Type Headers

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:11:41