将一个JSON NSData转换为NSDictionary



我正在使用一个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数据包是不完整的,但我不知道如何检查它或如何寻找应该位于我的代码中的问题。

你实现了nsurlconnectiondelegate的所有委托方法吗?看起来你正在从"- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data"委托方法进行数据转换。如果这样,您可能会得到不完整的数据,并且无法转换。

试试这个:

- (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的实例。

最新更新