将JSON NSData转换为NSDictionary

时间:2014-05-21 19:48:50

标签: ios objective-c json nsdictionary nsdata

我正在使用Web服务的API服务,并且在他们的描述中写道,他们发送的JSON数据在我看来也与我从中获得的响应相匹配。 这是我从NSURLConnection-Delegate(连接didReceiveData:(NSData *)数据)获得的一部分,并使用以下命令在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.}

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

1 个答案:

答案 0 :(得分:12)

你是否实现了NSURLConnectionDelagate的所有委托方法。看起来你正在从" - (void)连接获取转换数据:(NSURLConnection *)连接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;
}

此处, lookServerResponseData 是全局声明的NSMutableData实例。

希望它会有所帮助。