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

Swift结构体转JSON字符串失败,请求返回400错误求助

Hey there, let's dig into why your Swift JSON encoding is causing that 400 bad request while Postman works fine. Here are some targeted troubleshooting steps to pinpoint the issue:

1. Verify Struct Property Names & CodingKeys Match the API's JSON

APIs are strict about the key names they expect, and Swift's default JSON encoding uses your struct's property names directly. Mismatches here are a super common culprit.

  • If you haven't defined CodingKeys in your struct, double-check that every property name exactly matches the API's JSON keys (case sensitivity matters! Most APIs use snake_case while Swift uses camelCase by default).
  • Example fix for a key mismatch:
struct UserRequest: Codable {
    let userName: String
    let userEmail: String
    
    // Map Swift camelCase to API snake_case
    enum CodingKeys: String, CodingKey {
        case userName = "user_name"
        case userEmail = "user_email"
    }
}
2. Inspect the Exact Encoded JSON Payload

You need to see what Swift is actually sending to compare it with your working Postman request. Add this code right before you send your HTTP request:

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // Makes output human-readable
do {
    let jsonData = try encoder.encode(yourStructInstance)
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print("Encoded JSON Payload:\n\(jsonString)")
    }
} catch {
    print("Encoding Error: \(error.localizedDescription)")
}
  • Copy this printed JSON and compare it line-by-line with the raw request body from your working Postman call. Look for missing fields, incorrect data types, or formatting oddities (like extra commas or wrong date formats).
3. Tweak JSONEncoder Configuration

Postman might use specific formatting that your Swift encoder isn't replicating:

  • Date handling: If your struct includes Date properties, the API might expect a specific string format (like ISO 8601 with milliseconds). Configure the encoder accordingly:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
encoder.dateEncodingStrategy = .formatted(dateFormatter)
// Or use the built-in ISO 8601 strategy if that's what the API expects:
// encoder.dateEncodingStrategy = .iso8601
  • Auto snake_case conversion: If all your API keys use snake_case, you can avoid manual CodingKeys by setting:
encoder.keyEncodingStrategy = .convertToSnakeCase
4. Validate HTTP Request Headers

Even perfect JSON can fail if your headers are missing or wrong. Postman automatically sets headers that your Swift code might omit:

  • Make sure you're explicitly setting Content-Type: application/json in your request headers. Without this, the API might not recognize your payload as JSON.
  • Double-check for other required headers (like authorization tokens, API keys, or accept headers) that are present in Postman but missing in your Swift request code.
5. Capture & Compare Full Requests Side-by-Side

Use a tool like Charles Proxy or Wireshark to capture both the Postman request and your Swift app's request. Then compare every detail:

  • Request method (POST/PUT/etc. – make sure it's identical to Postman)
  • Full URL (including query parameters, if any)
  • All request headers (key-value pairs)
  • Exact request body content

The difference between the two requests will almost certainly point you to the fix.

内容的提问来源于stack exchange,提问作者SomeGuyFortune

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:17:38