使用 JSON 的 Cocoa 错误 3840 (iOS) [英] Cocoa error 3840 using JSON (iOS)

查看:25
本文介绍了使用 JSON 的 Cocoa 错误 3840 (iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据发送到服务器并接收 JSON 格式的响应.问题是服务器必须返回成功"或失败",但它返回(空)".

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 "操作不能完全的.(Cocoa 错误 3840.)"(JSON 文本未以数组或允许未设置片段的对象和选项.) UserInfo=XXXXXXXXX{NSDebugDescription=JSON 文本没有以数组或对象开头,并且允许未设置片段的选项.}

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.}

错误可能出在服务器脚本中吗?

Is it possible that the error is in the server script?

这是我发送数据和接收响应的函数:

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);
}

推荐答案

除非您将选项 NSJSONReadingAllowFragments 传递给 [NSJSONSerialization JSONObjectWithData:options:error:] 响应来自服务器必须是具有顶级容器的有效 JSON,该容器是数组或字典.

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.

例如:

    { "response" : "Success" }

附言如果你想要一个可变字典,你还必须在你的选项中包含 NSJSONReadingMutableContainers.

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

这篇关于使用 JSON 的 Cocoa 错误 3840 (iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆