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.
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 ??
[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.
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.
Further more you should evaluate the
error
object on every step when you get it to see which parsing of data cause this problem like:Also, as you said that:
Are you sure it is returning NS(Mutable)Dictionary ?? Try printing it like this:
In my case i was hitting POST Method instead of GET. Solved my problem.
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.
And when you are handling JSON data, you should never involve any NSString objects, except possibly to log data.
if the data is kind of josn ,you can
or
,so that you will be get nsdictionary or nsstring data, if you cannot parse it by yourself ,you can user jsonModel tranlte to model .
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
If you are populating json data from data base u have to use Nsarray. Hope this will help you .