无法读取数据,因为格式不正确 [英] The data couldn’t be read because it isn’t in the correct format

查看:5924
本文介绍了无法读取数据,因为格式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我现在开始使用iOS开发,目前使用Obj-C播放NSData。最近我使用URLSession:dataTask:didReceiveData方法使用 HTTP POST请求来获取NSData。服务器将响应包含JSON数组的JSON对象。

Ok, I am now starting with iOS development and currently playing with NSData using Obj-C. Recently I'm using the URLSession:dataTask:didReceiveData method to get NSData using HTTP POST request. The server will be responding a JSON object containing a JSON array.

有趣的是,当响应数据太大时,NSLog部分将打印out:数据无法读取,因为格式不正确 。下面是函数:

Something interesting is that when the response data is too large the NSLog part will print out: "The data couldn't be read because it isn't in the correct format". Below is the function:

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSError *error;
    // get data from NSData into NSDict
    NSDictionary *searchData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSArray *test = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSMutableDictionary *mdict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"what: %@", mdict);
    NSLog(@"received data length: %@", [NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);
    if (error) {
        NSLog(@"json error: %@", [error localizedDescription]);
    }
}

只是想知道是否有人知道导致此问题的潜在原因??

Just wondering if anyone knows the potential reason causing this problem ??

[更新]

嗯,解决此问题的另一种方法可能是使用NSString进行数据存储。但是我必须自己解析它。我更喜欢使用NSDictionary。

Well, an alternative to solve this problem might be using NSString for data storage. But would have to parse it by myself. I would prefer using NSDictionary though.

推荐答案

初学者问题:当某些数据时调用didReceiveData在数据完成之前已经到了。阅读didReceiveData的文档,它解释了您需要做什么。您正在尝试解析不完整的数据。那不行。

Beginner problem: didReceiveData is called when some of the data has arrived, before the data is complete. Read the documentation of didReceiveData, which explains what you need to do. You are trying to parse incomplete data. That won't work.

当您处理JSON数据时,除非可能记录数据,否则永远不会涉及任何NSString对象。

And when you are handling JSON data, you should never involve any NSString objects, except possibly to log data.

这篇关于无法读取数据,因为格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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