NSJSONSerialization解析字符串格式数据失败问题求助
NSJSONSerialization fail only when the API returns a plain string? Great question! Let’s break down exactly what’s happening here.
The Root Cause: NSJSONSerialization requires valid JSON
NSJSONSerialization strictly adheres to the JSON specification — it only parses data that fits the definition of valid JSON.
- Before iOS 13 and macOS 10.15, JSON’s top-level value was limited to objects (
{}) or arrays ([]). Even a string wrapped in double quotes (like"MY STRING") wouldn’t parse successfully on older OS versions. - On newer OS versions (iOS 13+/macOS 10.15+), the serializer supports top-level strings, numbers, booleans, and
null— but the string must still be properly wrapped in double quotes.
In your case, the data translates to the plain string MY STRING (no surrounding double quotes). This is not valid JSON by any standard, so NSJSONSerialization correctly returns nil because it can’t parse non-JSON data.
How to Fix This
You have two solid options depending on your control over the API:
Adjust the API to return valid JSON
The cleanest solution is to have the API wrap the string in a JSON object or array for consistency. Examples:- Object format:
{"result": "MY STRING"} - Array format:
["MY STRING"]
This ensures compatibility across all iOS/macOS versions.
- Object format:
Handle plain string responses in your code
If you can’t modify the API, add a fallback to handle cases where JSON parsing fails. Here’s how to adjust your method:NSError *error = nil; id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; // Fall back to string conversion if JSON parsing fails if (result == nil) { NSString *strResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // Return the string directly, or wrap it in a dictionary/array for consistent return types result = strResult ?: @"Failed to parse response"; } return result;Note: You might want to test other encodings (like
NSASCIIStringEncoding) if your API uses non-UTF8 character sets.
内容的提问来源于stack exchange,提问作者doxsi

