SoFunction
Updated on 2025-03-06

IOS development by converting NSDictionary into JSON string

IOS development by converting NSDictionary into JSON string

In general, you may use an NSDictionary classification to convert NSDictionary to JSON, as follows:

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
if (! jsonData) {
  return @"{}";
} else {
  return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

However, the data types installed by NSDictionary are mixed, and may be Objective-C objects such as NSDate, NSNumber, and NSValue.[NSJSONSerialization dataWithJSONObject:options:error:]This method cannot parse these objects. If there are these objects, it will cause crash. So we should add a step before calling NSJSONSerialization to process all data into NSString, the code is as follows:

NSError *error = nil;
NSData *jsonData = nil;
if (!self) {
  return nil;
}
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  NSString *keyString = nil;
  NSString *valueString = nil;
  if ([key isKindOfClass:[NSString class]]) {
    keyString = key;
  }else{
    keyString = [NSString stringWithFormat:@"%@",key];
  }

  if ([obj isKindOfClass:[NSString class]]) {
    valueString = obj;
  }else{
    valueString = [NSString stringWithFormat:@"%@",obj];
  }

  [dict setObject:valueString forKey:keyString];
}];
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if ([jsonData length] == 0 || error != nil) {
  return nil;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;

In this way, NSDictionary will not crash if it is converted to JSON. Similarly, NSArray should do the same.

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!