将 JSON NSData 转换为 NSDictionary

2024-01-04

我正在使用 Web 服务的 API 服务,在他们的描述中写道,他们发送 JSON 数据,在我看来,这些数据也与我从中得到的响应相匹配。

这是我从 NSURLConnection-Delegate (connection didReceiveData: (NSData *) data) 获得的一部分,并使用以下方法转换为 NSString:

NSLog(@"response: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

这里是片段:

{"scans": 
{
    "Engine1“: 
    {
        "detected": false, 
        "version": "1.3.0.4959", 
        "result": null, 
        "update": "20140521"
    }, 
    "Engine2“: 
    {
        "detected": false,
         "version": "12.0.250.0",
         "result": null,
         "update": "20140521"
    }, 
        ...
    },
    "Engine13": 
    {
         "detected": false,
         "version": "9.178.12155",
         "result": 

在 NSLog-String 中,它停在那里。现在我想知道你出了什么问题,我无法使用以下代码行将此数据转换为 JSON 字典:

NSError* error;
    NSMutableDictionary *dJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

我尝试了一些选项,但总是出现相同的错误:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" 
(Unexpected end of file while parsing object.) UserInfo=0x109260850 {NSDebugDescription=Unexpected end of file while parsing object.}

一切都表明 JSON 数据包不完整,但我不知道如何检查它或如何查找应该位于我的代码中的问题。


您是否实现了 NSURLConnectionDelagate 的所有委托方法。看起来您正在从“- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data”delagate 方法获取数据进行转换。如果是这样,您可能会得到不完整的数据并且无法转换。

尝试这个:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    lookServerResponseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to the instance variable you declared
    [lookServerResponseData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    NSError *errorJson=nil;
    NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:lookServerResponseData options:kNilOptions error:&errorJson];

     NSLog(@"responseDict=%@",responseDict);

    [lookServerResponseData release];
    lookServerResponseData = nil;
}

Here, 查看服务器响应数据是全局声明的 NSMutableData 的实例。

希望它会有所帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 JSON NSData 转换为 NSDictionary 的相关文章

随机推荐