ios 无法读取数据,因为它的格式不正确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37825284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:22:57  来源:igfitidea点击:

The data couldn’t be read because it isn’t in the correct format

iosobjective-cjson

提问by 4Gred__

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.

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

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:

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

-(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 ??

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

[Update]

[更新]

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.

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

回答by gnasher729

Beginner problem: didReceiveData is called when someof 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.

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

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

当你正在处理JSON数据,你应该永远不会涉及任何NSString对象,可能除了记录数据。

回答by Rahul

In my case i was hitting POST Method instead of GET. Solved my problem.

就我而言,我使用的是 POST 方法而不是 GET。解决了我的问题。

回答by NeverHopeless

At first point you should check if the response received from the API is a valid JSON, can be check by online validators like jsonlint.com. If this is a vaid json, then you are good to go.

首先,您应该检查从 API 收到的响应是否是有效的 JSON,可以通过在线验证器(如jsonlint.com)进行检查。如果这是一个无效的 json,那么您就可以开始了。

Further more you should evaluate the errorobject on every step when you get it to see which parsing of data cause this problem like:

此外,error当您获得对象时,您应该在每一步评估该对象,以查看哪些数据解析会导致此问题,例如:

    NSError *error;
    // get data from NSData into NSDict
    NSDictionary *searchData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

    if (error) {
        NSLog(@"json error: %@", [error localizedDescription]);
    }

    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]);
    }

Also, as you said that:

另外,正如你所说:

The server will be responding a JSON object containing a JSON array.

服务器将响应包含 JSON 数组的 JSON 对象。

Are you sure it is returning NS(Mutable)Dictionary ?? Try printing it like this:

你确定它正在返回 NS(Mutable)Dictionary 吗??尝试像这样打印:

    id response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

    if (error) {
        NSLog(@"json error: %@", [error localizedDescription]);
    }
    else
    {
        NSLog(@"json data : %@", response);
    }

回答by scandy

if the data is kind of josn ,you can

如果数据是一种 josn ,你可以

NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

or

或者

[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]) 

,so that you will be get nsdictionary or nsstring data, if you cannot parse it by yourself ,you can user jsonModel tranlte to model .

,这样你就会得到nsdictionary或nsstring数据,如果你自己不能解析它,你可以使用jsonModel tranlte来建模。

回答by Madhu Kiran

It may be a problem with your json data I have experienced the same. You have to serialize your json data like this below written code

你的json数据可能有问题,我也遇到过。您必须像下面这样编写的代码序列化您的json数据

NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

If you are populating json data from data base u have to use Nsarray. Hope this will help you .

如果您要从数据库填充 json 数据,则必须使用 Nsarray。希望这会帮助你 。