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:
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
CodingKeysin 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" } }
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).
Postman might use specific formatting that your Swift encoder isn't replicating:
- Date handling: If your struct includes
Dateproperties, 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
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/jsonin 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.
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

