Method to resolve that JSON data failed to load because of null

  • 2020-11-03 22:37:02
  • OfStack

1. First analyze the problem:

Using NSJSONSerialization or AFN framework AFHTTPSessionManager (also NSJSONSerialization at the bottom) to convert NSData data to OC object, sometimes URL correct, loading data will still report an error:


 reason: '-[NSNull length]: unrecognized selector sent to instance

Analysis of the reason found that the transformed OC object contains null. Therefore, NSNull does not have an length method, so it will report no method error found.

2. Solution: Replace "null" with "".

1. First convert NSData data to NSString;

2. Replace the converted NSString;

3. Replace the NSSting and convert it into NSData;

4.NSData converted to OC object

The following provides a good encapsulation method, directly used in the future


// Replaces an empty string in the data 
+ (NSArray*)arrayWithNoNullArray:(NSArray*)originalArray {
  //array -> string
  NSData *data = [NSJSONSerialization dataWithJSONObject:originalArray options:0 error:nil];
  NSString *str =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  // replace 
  NSString *nStr = [str stringByReplacingOccurrencesOfString:@"null" withString:@"\"\""];
  //string -> array
  NSData *nData =[nStr dataUsingEncoding:NSUTF8StringEncoding];
  return [NSJSONSerialization JSONObjectWithData:nData options:0 error:nil];
}

An OC array containing null is passed in, and the replacement array is returned directly. If you load the data with an array without null, you'll be fine.

Well, the above is the solution to JSON data because null led to the failure of data loading method, I hope to have help to friends in need, if there is any question to hit you can leave a message to communicate.


Related articles: