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

NSJSONSerialization解析字符串格式数据失败问题求助

Why does 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:

  1. 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.
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:11:56