ios – 将JSON NSData转换为NSDictionary

前端之家收集整理的这篇文章主要介绍了ios – 将JSON NSData转换为NSDictionary前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Web服务的API服务,并且在他们的描述中写道,他们发送的 JSON数据在我看来也与我从中获得的响应相匹配.
这是我从NSURLConnection-Delegate(连接didReceiveData:(NSData *)数据)获得的一部分,并使用以下命令在NSString中转换:
  1. NSLog(@"response: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

这里的片段:

  1. {"scans":
  2. {
  3. "Engine1“:
  4. {
  5. "detected": false,"version": "1.3.0.4959","result": null,"update": "20140521"
  6. },"Engine2“:
  7. {
  8. "detected": false,"version": "12.0.250.0",...
  9. },"Engine13":
  10. {
  11. "detected": false,"version": "9.178.12155","result":

在NSLog-String中它停在那里.现在我想知道你错了,我不能用这行代码将这些数据转换为JSON字典:

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

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

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

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

解决方法

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

试试这个:

  1. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  2. {
  3. // A response has been received,this is where we initialize the instance var you created
  4. // so that we can append data to it in the didReceiveData method
  5. // Furthermore,this method is called each time there is a redirect so reinitializing it
  6. // also serves to clear it
  7. lookServerResponseData = [[NSMutableData alloc] init];
  8. }
  9.  
  10. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  11. {
  12. // Append the new data to the instance variable you declared
  13. [lookServerResponseData appendData:data];
  14. }
  15.  
  16.  
  17. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  18. {
  19. // The request is complete and data has been received
  20. // You can parse the stuff in your instance variable now
  21. NSError *errorJson=nil;
  22. NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:lookServerResponseData options:kNilOptions error:&errorJson];
  23.  
  24. NSLog(@"responseDict=%@",responseDict);
  25.  
  26. [lookServerResponseData release];
  27. lookServerResponseData = nil;
  28. }

这里,lookServerResponseData是全局声明的NSMutableData的实例.

希望它会有所帮助.

猜你在找的iOS相关文章