I'm trying to send data to a server and receive the response in JSON format. The problem is that the server has to return "success" or "fail" but it returns "(null)".

以下是返回的错误:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=XXXXXXXXX {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

服务器脚本中是否可能存在错误?

Here's my function to send the data and receive the response:

- (void) putData:(NSString *)parameter valor:(NSString *)valor {

    NSString *rawString = [NSString stringWithFormat:@"%@=%@", parameter, valor];
    NSData *data = [rawString dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://www.xxx.xxx/xxx.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"PUT"];
    [request setHTTPBody:data];
    NSURLResponse *response;
    NSError *error;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSLog(@"responseData: %@ error: %@", json, error);
}

推荐答案

Unless you pass the option NSJSONReadingAllowFragments to [NSJSONSerialization JSONObjectWithData:options:error:] the response from the server must be valid JSON with a top level container which is an array or dictionary.

for example:

    { "response" : "Success" }

P.S. If you want a mutable dictionary you must also include NSJSONReadingMutableContainers in your options.

Json相关问答推荐

手动解开没有可编码的SON- Swift

Vega Lite中的图例对齐

如何用JQ更改空/布尔/数字的 colored颜色 ?

将PostgreSQL转换为JSON对象

将 std::可选值存储到 json 文件 C++

如何使用Powershell查找所有包含特定键值对的JSON对象并迭代所有对象?

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

颠簸转换问题

无法在Kotlin 中解析JSONObject

Rails 控制器无需编码即可渲染 json

如何使用 jq 返回此 JSON 文件的文本字段?

在 JavaScript 中从 Json 数据中删除反斜杠

什么是类型和类型令牌?

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

Spring Security 和 JSON 身份验证

ASP.NET Core API 仅返回列表的第一个结果

使用 application/json 优于 text/plain 的优势?

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)

从调试器获取 IntelliJ Idea 中的 JSON 对象

如何在 postgresql 9.3 中循环 JSON 数组