求助:AnyHashable字典转[String:Any]时payload被转为String的修复方案
[AnyHashable: Any] to [String: Any] Hey there! I totally get the frustration—your payload should stay a native dictionary, but right now it's getting locked as a JSON string after the conversion. Let's work through this fix step by step.
The Root Problem
Your current conversion loop just copies values over directly, but the server is sending the payload as a JSON-encoded string (not a ready-to-use dictionary). So we need to add a check for this specific key and parse the string back into a dictionary.
Step-by-Step Solution
First, let's make a helper function to safely turn JSON strings into dictionaries—this handles parsing errors gracefully so your app doesn't crash if the JSON is malformed:
func parseJSONStringToDictionary(_ jsonString: String) -> [String: Any]? { guard let data = jsonString.data(using: .utf8) else { return nil } do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print("Payload JSON parsing failed: \(error.localizedDescription)") return nil } }
Next, update your conversion loop to add special handling for the payload key:
let hashableDictionary: [AnyHashable: Any] = [:] // Your server-provided dictionary var normalDictionary: [String: Any] = [:] for (key, value) in hashableDictionary { let stringKey = key.description // Handle payload specifically if stringKey == "payload", let payloadString = value as? String { // Try to convert the JSON string to a dictionary if let parsedPayload = parseJSONStringToDictionary(payloadString) { normalDictionary[stringKey] = parsedPayload } else { // Fallback: keep the original string if parsing fails normalDictionary[stringKey] = payloadString } } else { // For all other keys, copy the value as-is normalDictionary[stringKey] = value } }
Key Details
- Safety: The helper function includes error handling, so invalid JSON won't break your app—it'll just keep the original string.
- Backward Compatibility: All other keys in your dictionary keep their original behavior; we only modify the
payloadhandling. - Explicit Checks: We first confirm the value is a string before trying to parse it, avoiding wasted work if the server ever sends
payloadas a native dictionary later.
After running this code, normalDictionary["payload"] will be a [String: Any] dictionary with keys like type_nm, crcd_dt, and read—exactly what you need!
内容的提问来源于stack exchange,提问作者Harsha

